Z Index in CSS
z-index in CSS — Controlling Stack Order of Elements
The z-index property controls the vertical stacking order of overlapping elements on a webpage. Elements with a higher z-index appear in front of those with lower values.
How z-index Works
Only works on elements with a positioning context (
position: relative,absolute,fixed, orsticky).Default
z-indexisauto(usually 0).Higher
z-index= closer to the viewer (on top).Elements with the same
z-indexfollow HTML source order (later elements are on top).
Syntax
.element { position: relative; /* or absolute, fixed, sticky */ z-index: 10; /* integer value */}Example
<div class="box1">Box 1</div><div class="box2">Box 2</div>.box1 { position: absolute; left: 50px; top: 50px; width: 150px; height: 150px; background: red; z-index: 1; /* behind box2 */}.box2 { position: absolute; left: 100px; top: 100px; width: 150px; height: 150px; background: blue; z-index: 2; /* in front of box1 */}Important Notes
z-indexonly works on positioned elements.Negative values are allowed (can send elements behind others).
Stacking contexts affect how
z-indexworks; a new stacking context is created by:position+z-indexnotautoopacityless than 1CSS transforms, filters, flex containers, etc.
Quick Reference
| Value | Effect |
|---|---|
auto | Default stacking order |
0 | Base layer |
| Positive | Stacks above elements with lower |
| Negative | Stacks below elements with zero or positive |
Want me to show you examples with stacking contexts or help debug a z-index problem?