When elements overlap, which one is on top? That is the stacking order, and z-index is how you change it. Think of the page as layers of paper: a higher number is closer to you.
<style>
.box { position: absolute; width: 90px; height: 90px; padding: 6px; color: #fff; }
.a { background: #1a5276; top: 10px; left: 10px; z-index: 1; }
.b { background: #d94a00; top: 40px; left: 40px; z-index: 2; }
.c { background: #27ae60; top: 70px; left: 70px; z-index: 0; }
.stage { position: relative; height: 180px; }
</style>
<div class="stage">
<div class="box a">1</div>
<div class="box b">2</div>
<div class="box c">0</div>
</div>
The orange box (2) is on top, the blue (1) in the middle and the green (0) at the bottom, although the green one comes last in the HTML.
Without z-index
If nothing has a z-index, later elements in the HTML are drawn on top of earlier ones.
When z-index does nothing
z-index works only on:
- elements with a
positionother thanstatic, and - flex or grid items (they do not need a position).
If you set it on a plain static element, nothing happens.
Stacking contexts
This is the part that confuses people. Some properties create a stacking context: a self-contained group of layers. They are position with a z-index, opacity below 1, transform, filter and a few others.
Inside a stacking context, children are only compared with each other. A child with z-index: 9999 inside a parent with z-index: 1 still cannot rise above a sibling of that parent that has z-index: 2.
z-index wars
z-index: 99999 is rarely the answer. Look for the stacking context of the ancestors. Keep your z-index values small and organized: for example 10 for dropdowns, 20 for sticky headers and 30 for modals.