Layers on the screen
When boxes overlap, the browser must decide which appears in front. Z index orders elements along the depth axis, but it only works among siblings inside the same stacking context.
What creates a context
A stacking context is a self contained group whose children are stacked together, then the whole group is placed as one unit in its parent. Several things create one:
- The root element.
- An element with a z index and a position other than static.
- Opacity below one, a transform, a filter, or will change.
The common surprise
A child with z index of a million can still sit behind another box if its parent forms a stacking context that sits lower. The child can never escape its parent context. To fix layering bugs, find which ancestor created the context, not just the elements you see.
Key idea
Z index only orders siblings within the same stacking context, so a child can never rise above an element outside its parent context no matter how high its value.