Beginner LevelCSS & Modern Layouts
How does z-index and stacking context work in CSS?
❓ Interview Prompt: Explain z-index, stacking contexts, and why z-index sometimes seems to not work.
z-index controls the visual stacking order of overlapping positioned elements (relative, absolute, fixed, sticky).
Key Rules:
1
z-index only works on elements with position other than static (or flex/grid children).2
Elements with higher
z-index render on top of elements with lower values.3
A stacking context is created by certain properties (
z-index on positioned element, opacity < 1, transform, filter, will-change). Child z-index values are scoped within their parent stacking context.Why z-index "Doesn't Work":
If parent A has z-index: 1 and parent B has z-index: 2, no child inside A can ever appear above B — because child z-indexes are scoped to their parent context.
Code Implementation Example
css
/* Layered stacking order */
.modal-backdrop { position: fixed; z-index: 1000; }
.modal-content { position: fixed; z-index: 1001; }
.tooltip { position: absolute; z-index: 500; }
.navbar { position: sticky; z-index: 100; }
/* Caution: transform creates a new stacking context */
.card {
transform: translateZ(0); /* This isolates z-index scope */
}💡Stacking layers for modals, tooltips, and navigation.
🎯 Interview Key Takeaway
z-index is scoped to stacking contexts. A child can never escape its parent stacking context layer.
#z-index#Stacking#Layers#Beginner
Back to all CSS & Modern Layouts Questions→