What is a Stacking Context?
You'll learn what stacking contexts are and how they create independent layers that control how elements stack in 3D space.
When you use positioning properties like position: relative, absolute, fixed, or sticky, elements can overlap. But CSS doesn't just pile them on top of each other randomly—it creates stacking contexts, which are like independent 3D layering environments that determine what appears in front and what goes behind.
The Core Idea
Think of a stacking context like a deck of cards. Once you bundle several cards together and place them on the table, those cards stay grouped together as one unit. The cards inside the deck maintain their order relative to each other, but the entire deck moves as one piece when you compare it to other objects on the table.
In CSS, certain properties create these "decks"—these are stacking contexts. Inside a stacking context, child elements are stacked according to specific rules (like their z-index values). But here's the key: a stacking context is completely independent. Elements inside one context can never appear between elements of another context, no matter their z-index values.
What Creates a Stacking Context?
Positioned elements with a z-index value other than auto create new stacking contexts. For example, an element with position: relative and z-index: 1 forms its own stacking context.
Why This Matters
Understanding stacking contexts prevents confusion when z-index doesn't seem to work. If two elements belong to different stacking contexts, comparing their z-index values is meaningless—what matters is the stacking order of their parent contexts.
Key Takeaway: A stacking context is an independent 3D layer that groups elements together; child elements stack within their context but cannot interleave with elements from other contexts, no matter their z-index.