CSS Z-index
31 March 2025 | Category: CSS
The z-index property in CSS is used to control the stack order of elements. It determines which element appears on top when elements overlap.
1️⃣ Syntax
selector {
position: relative | absolute | fixed | sticky;
z-index: value;
}
✅ Possible Values
| Value | Description |
|---|---|
auto | Default. The element follows the stacking order. |
number | Higher numbers appear on top of lower ones. |
negative | Elements with negative z-index appear behind others. |
⚠️ z-index only works on positioned elements (relative, absolute, fixed, or sticky).
⚠️ z-index does NOT work on elements with position: static.
2️⃣ How z-index Works
Elements are stacked in the following order (from bottom to top):
- Background (default elements)
- Elements with
position: static - Elements with
position: relative - Elements with
position: absolute - Elements with
position: fixed - Elements with
z-index(higher values appear on top)
3️⃣ Example: Basic z-index Usage
.box1 {
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background: red;
z-index: 1; /* Lower priority */
}
.box2 {
position: absolute;
top: 70px;
left: 70px;
width: 100px;
height: 100px;
background: blue;
z-index: 2; /* Higher priority (appears on top) */
}
✅ Result: The blue box appears on top of the red box because z-index: 2 is greater than z-index: 1.
4️⃣ Negative z-index (Behind Other Elements)
.box {
position: relative;
z-index: -1;
}
✅ Use Case: Place an element behind other elements (like background decorations).
5️⃣ z-index with Parent Elements
If a parent has z-index: 1 and a child has z-index: 999, the child cannot escape its parent’s stacking order.
.parent {
position: relative;
z-index: 1;
}
.child {
position: absolute;
z-index: 999; /* Still inside parent, can't go above other elements outside */
}
6️⃣ z-index in Practical Use Cases
✅ Dropdown Menu Above Everything
.menu {
position: absolute;
z-index: 1000; /* Ensures it's above all elements */
}
✅ Modal (Popup) on Top
.modal {
position: fixed;
z-index: 9999;
}
✅ Sticky Header Above Content
.header {
position: sticky;
top: 0;
z-index: 100;
}
🎯 Summary
z-index Value | Effect |
|---|---|
auto | Default stacking order. |
Positive z-index | Element moves on top of lower values. |
Negative z-index | Element moves behind other elements. |
z-index inside parent | A child’s z-index is limited by the parent’s z-index. |
💡 Use z-index wisely to control stacking order! 🚀