The z-index property in CSS controls the stacking order of elements along the z-axis (depth).
- Higher
z-index→ element appears on top of elements with lowerz-index. - Only works on positioned elements (
position: relative,absolute,fixed, orsticky). - Default
z-indexisauto(0 in stacking context).
🔹 Basic Example
.box1 {
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background-color: red;
z-index: 1;
}
.box2 {
position: absolute;
top: 80px;
left: 80px;
width: 100px;
height: 100px;
background-color: blue;
z-index: 2; /* appears on top */
}
✅ Behavior: The blue box will overlap the red box because its z-index is higher.
🔹 Important Points
- Positioning required:
z-indexhas no effect onposition: static. - Stacking context: Certain properties (like
opacity < 1,transform) create a new stacking context, which can affect howz-indexworks. - Negative values: Allowed. Elements with negative
z-indexcan appear behind the parent.
💡 In Short:
z-indexcontrols which element appears on top when elements overlap, but only works for positioned elements within the same stacking context.