Layering along the z axis
The z index property controls paint order for positioned boxes along the depth axis. A larger value paints in front of a smaller one, but only when the boxes share the same stacking context. This is why a z index of nine thousand can still sit behind a sibling with a much smaller value.
- z index only applies to positioned or flex and grid items.
- Within one context, larger values paint on top.
- The value is meaningless across different contexts.
What creates a context
A stacking context is a self contained layering group. Once an ancestor forms one, its descendants can never escape it to compare against outside boxes.
- The root element forms the base context.
- A positioned element with a z index forms one.
- Opacity below one, a transform, a filter, or will change forms one.
When stacking goes wrong, the fix is usually finding the ancestor that created an unexpected context, not raising numbers higher.
Key idea
z index orders boxes only inside a shared stacking context, and properties like opacity and transform silently create new contexts that trap their descendants.