Creating Stacking Contexts with z-index
You'll learn: How combining positioned elements with z-index creates isolated stacking environments that affect how child elements layer.
The Core Idea
When you apply a z-index value to a positioned element (relative, absolute, fixed, or sticky), you don't just control its layering—you create a brand new stacking context for all of its descendants. Think of it like starting a fresh deck of cards: the parent becomes layer zero in its own mini-universe, and all children stack relative to that parent, not the page root.
This means a child element inside a stacking context can never escape to layer above or below elements outside its parent's stacking context, no matter how high or low you set its z-index.
How It Works
Imagine two boxes: Box A has position: relative; z-index: 1, and Box B has position: relative; z-index: 2. Box B sits on top, as expected.
Now give Box A a child with z-index: 9999. That child will still appear below Box B, because it's trapped inside Box A's stacking context. The child's z-index only matters relative to other elements within Box A's context—it can't "break out" to compete with Box B.
Why This Matters
Understanding this prevents frustrating layering bugs. You might crank a dropdown's z-index to 99999 and wonder why it still hides behind a modal. The answer: they're in different stacking contexts, and the modal's parent context has a higher z-index.
Key Takeaway: A positioned element with a z-index value creates a new stacking context, making all descendants stack independently from the rest of the page within that isolated layer.