CSS · Layout and visual systems
Why does z-index sometimes not work?
Short answer
z-index only applies to positioned elements and certain layout items, and it is scoped to a stacking context. A high z-index inside a lower context cannot escape above a sibling context.
Stacking contexts are local stacking universes. Elements are painted according to the context they belong to, so comparing z-index values across different contexts is meaningless. The context itself participates in its parent's stacking order.
.card {
position: relative;
z-index: 1;
}
.modal {
position: fixed;
z-index: 1000;
}
.overlay {
position: absolute;
isolation: isolate;
z-index: 2;
}What creates a stacking context
- The root element
- A positioned element with a z-index other than auto
- Opacity less than 1, transform, filter, perspective or clip-path
- isolation: isolate
- will-change naming a property that would create one
- Containment, mix-blend-mode and some other properties
- A flex or grid item with a z-index other than auto
Paint order also matters within a context: backgrounds and borders first, then negative z-index children, block-level descendants, floats, inline content, positioned elements with z-index auto or zero, and finally positive z-index children.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What creates a stacking context?
- 2Why can a child with z-index 9999 appear behind another element?
- 3Does z-index work on a static element?
- 4What does isolation: isolate do?
Say it in the interview
z-index only works within a stacking context and only applies to positioned elements or certain layout items. If an ancestor creates a stacking context, a child's z-index is scoped to that context and cannot beat a sibling context with a higher position in the parent stack. Transform, opacity, filter and isolation all create contexts. When z-index fails, I inspect ancestors before raising the number.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live CSS mock interview and get scored feedback on depth, clarity and confidence.