z-index
Which positioned element is drawn on top when they overlap.
Syntax
z-index: number;Values
| Parameter | Type | Description |
|---|---|---|
| number | integer | A larger number is drawn above a smaller one; it can be negative. |
| auto | keyword | The order of the elements in the markup (the default). |
Examples
The first block is on top although the second comes later:
<style>
.box { position: relative; width: 120px; height: 70px; padding: 6px; color: white; }
.a { background: royalblue; z-index: 2; }
.b { background: crimson; margin: -40px 0 0 40px; z-index: 1; }
</style>
<div class="box a">z-index: 2 — on top</div>
<div class="box b">z-index: 1</div>Notes
z-index works on positioned elements and on flex and grid items. Elements are compared only within the same stacking context: a child with z-index: 9999 cannot rise above the neighbor of its parent if the parent itself is lower. Contexts are also created by opacity below 1, transform and filter.
See also
Related recipes
In the tutorial
- Overflow and layers — What to do when content does not fit into a block — overflow, scrolling, an ellipsis — and how z-index decides which element lies on top.