HTML & CSS - Mastery / Layout Fundamentals

Z-Index and Stacking Elements

⚡️ Understanding Z Index

The z-index property controls the vertical stacking order of elements on the page (like layers).

🧠 Basic Rules

  • Higher z-index = closer to the viewer (on top).

  • Works only on elements with a position value other than static (relative, absolute, fixed, or sticky).

  • Elements with equal z-index stack in the order they appear in the DOM (later ones on top).


🔢 Syntax Example


📚 How Stacking Context Works

A stacking context is like a mini-universe of layers. When an element creates a new stacking context, all its children are stacked inside it.

Stacking context is triggered by:

  • positioned elements with z-index (not auto)

  • Elements with opacity < 1, transform, filter, will-change, etc.

👇 Example with Explanation

Even though child1 has a higher z-index (10) than child2 (5), both are inside .parent, which has a stacking level of z-index: 1.

So, if there's another element outside .parent with z-index: 2, it will appear above the entire .parent, no matter how high the children’s z-indexes are inside.

For Example:


🧩 Real-World Use Cases

  • Modal popups → z-index: 9999

  • Sticky navbars above content → z-index: 100

  • Tooltips and dropdowns → z-index: 500