Stacking context in CSS is the concept that defines how elements are layered (stacked on the z-axis) — i.e., which element appears on top of another.
π§± What is a Stacking Context?
A stacking context is a self-contained stacking order for elements.
Once an element creates a stacking context, its children are stacked only within that context, not compared with elements outside it.
π Think of it as a mini z-index world.
π How a Stacking Context Is Created
An element creates a new stacking context when it has:
β Common cases
position: relative | absolute | fixed | sticky;
z-index: any value except auto;
opacity: less than 1;
transform: translate() | scale() | rotate();
filter: blur();
perspective;
isolation: isolate;
will-change: transform;
contain: layout | paint;
π§ͺ Example
.parent {
position: relative;
z-index: 1;
}
.child {
position: absolute;
z-index: 999;
}
Even with z-index: 999, .child cannot overlap elements outside .parent's stacking context.
β οΈ Common Confusion (Interview Favorite)
.modal {
z-index: 1000;
}
But it still appears behind another element β
π§ Reason:
- The modal is inside a lower stacking context
- z-index only works within the same stacking context
π Stacking Order (Simplified)
Within a stacking context, elements are layered in this order:
- Background & border of element
- Negative z-index children
- Normal flow elements
- Positioned elements (
z-index: auto) - Positive z-index elements
π― Why Stacking Context Is Important
β Prevents unexpected overlaps
β Explains z-index bugs
β Crucial for modals, dropdowns, tooltips
β Helps debug UI layering issues
π― Short Interview Answer
A stacking context is a CSS concept that defines how elements are stacked along the z-axis.
It is created by certain CSS properties likepositionwithz-index,opacity, ortransform.
Elements are stacked only within their own stacking context, which explains many z-index issues.
β One-line summary
z-index works only within the same stacking context — not globally.