🧱 CSS z-index
— Control Stacking Order of Elements
The z-index
property controls the stacking order of positioned elements (elements with position
set to relative
, absolute
, fixed
, or sticky
). It determines which elements appear in front of or behind others on the z-axis (depth).
🔹 What Does z-index
Do?
- Controls layering of elements along the z-axis.
- Higher
z-index
values are displayed on top of lower ones. - Only works on elements that have a
position
other thanstatic
(default).
📘 Syntax
selector {
position: relative | absolute | fixed | sticky; /* required for z-index to work */
z-index: auto | <integer>;
}
<integer>
can be positive, negative, or zero.auto
means default stacking order.
✅ How It Works
- Elements with higher
z-index
appear in front. - Elements with the same
z-index
follow the order they appear in the HTML. z-index
only affects elements that are positioned (relative
,absolute
, etc.).
✍️ Examples
1. Basic Stacking
.box1 {
position: relative;
z-index: 1;
background: red;
width: 100px;
height: 100px;
}
.box2 {
position: relative;
z-index: 2;
background: blue;
width: 100px;
height: 100px;
margin-top: -50px;
margin-left: 50px;
}
✅ .box2
(blue) will appear on top of .box1
(red) because it has a higher z-index
.
2. Negative z-index
.box {
position: absolute;
z-index: -1;
background: green;
width: 150px;
height: 150px;
}
✅ The green box will be behind other elements with z-index
≥ 0.
🖼️ Image Idea: Stacking Layers
Visualize overlapping colored squares with different z-index
values, showing how higher values overlay lower ones.
💡 Tips for Using z-index
- Always set
position
forz-index
to take effect. - Use integers carefully to manage stacking contexts.
- Beware of creating too many stacking contexts, which can complicate layout.
- Use browser dev tools to inspect stacking order.
✅ Summary
Property | z-index |
---|---|
Purpose | Control stacking order of positioned elements |
Works with | Elements with position other than static |
Values | auto (default), positive/negative integers |
Effect | Higher values stack on top of lower ones |
🔚 Final Thought
z-index
is essential for managing which elements appear on top in complex layouts, popups, modals, dropdowns, and more. Use it wisely for clear visual hierarchy.