z-index
Determines which element sits on top when elements overlap.
- Initial value
auto- Inherited
- No
- Animatable
- yes, as an integer
- Applies to
- positioned elements, flex items, and grid items
- JavaScript
element.style.zIndex = "10"
Example
#.header {
position: sticky;
top: 0;
z-index: 10;
}<div class="stage" style="height: 130px; overflow: auto; padding: 0;">
<div class="header box" style="border-radius: 0">Sticky header above the content</div>
<p style="padding: 0 12px">Scroll. The content moves under the header because it has a higher z-index.</p>
<p style="padding: 0 12px; position: relative;">A paragraph with position: relative.</p>
<p style="padding: 0 12px">Another paragraph.</p>
<p style="padding: 0 12px">And one more.</p>
</div>Definition and usage
#The z-index property sets the stacking order on the axis perpendicular to the screen. An element with a higher value covers elements with a lower one. It works on positioned elements as well as on children of flex and grid containers.
The key concept is the stacking context. Elements only compare their z-index within the same context. If a parent creates its own context (for example through z-index, an opacity below 1, or transform), its children can’t rise above elements outside it, even with a value of 9999.
Without a z-index set, elements overlap in the order they appear in the code: a later one covers an earlier one.
Syntax
#z-index: auto | <integer>;Values
#Values in practice
#auto
.demo { z-index: auto; }3
.demo { z-index: 3; }-1
.demo { z-index: -1; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Instead of competing with values like 9999, settle on a scale, for example 10 for the header, 100 for the menu, and 1000 for modal windows.
- When
z-index"doesn’t work," look for an ancestor that creates a new stacking context throughtransform,opacity, orfilter.
Related entries
#Spotted a mistake or missing an example? Write to us.