CSS z-index
Theory & Explanation
z-index is a CSS property that controls the vertical stacking order of positioned elements (those with position set to relative, absolute, fixed, or sticky). Elements with a higher z-index value appear in front of those with a lower value. z-index only works on elements that create a stacking context.
- Default stacking: Elements are stacked in the order they appear in the HTML (later elements on top).
- z-index: Assigns a stacking level. Higher values are closer to the viewer.
- Stacking context: Created by elements with
position (not static) and a z-index value, opacity < 1, transform, filter, will-change, mix-blend-mode, etc.
- Nested stacking: Each stacking context is independent; child z-index values are relative to their parent context.
When to Use z-index
- To control which overlay, modal, tooltip, or dropdown appears above others.
- To resolve stacking issues with positioned elements.
- To create layered UI effects (cards, popups, sticky headers, etc.).
Best Practices
- Use the smallest z-index values needed to avoid confusion.
- Minimize the number of stacking contexts for easier debugging.
- Document z-index values in your codebase for maintainability.
Code Examples
/* Basic z-index */
.box1 { z-index: 1; }
.box2 { z-index: 2; }
/* Stacking context */
.parent {
position: relative;
z-index: 10;
}
.child {
position: absolute;
z-index: 2;
}
Interactive Demos
Default stacking (no z-index)
Later elements appear on top by default.
z-index stacking
z-index: 1
z-index: 3
z-index: 2
Box with higher z-index appears on top, regardless of HTML order.
Stacking context (nested)
Parent (z-index: 10)
Child (z-index: 2)
Outside (z-index: 5)
Child's z-index is relative to its parent stacking context, not the page.
Hover over the boxes to see their stacking visually. Try changing the z-index values in the code for different effects.
← Back to Home