Z-index & Layering in CSS
The z-index
property in CSS controls the vertical stacking order of elements. It is especially useful when elements overlap and you want to control which one appears on top.
1. How Z-index Works
The z-index
only works on positioned elements (position: relative
, absolute
, fixed
, or sticky
). Higher values appear above lower values.
.box1 {
position: absolute;
z-index: 1;
}
.box2 {
position: absolute;
z-index: 5;
}
In this example, .box2
will appear above .box1
.
2. Default Stacking Context
Elements are stacked based on their order in the HTML by default. Later elements appear above earlier ones if z-index
is not used.
3. Creating a New Stacking Context
Some properties (like position
+ z-index
, opacity
< 1, transform
, filter
, etc.) create a new stacking context. This confines z-index comparisons within that context.
.container {
position: relative;
z-index: 10;
}
.child {
position: absolute;
z-index: 999;
/* Still below other containers with higher z-index */
}
4. Negative Z-index
You can assign negative z-index values to send elements behind others — even behind the page's background in some cases.
.behind {
position: absolute;
z-index: -1;
}
5. Practical Tips
- Use
z-index
sparingly to avoid unexpected stacking issues. - Set
position
whenever usingz-index
. - Use layers (e.g., modals, dropdowns) with high
z-index
like 9999+ for safety. - Understand stacking context to debug layering problems.
Conclusion
The z-index
property gives you control over which elements appear in front or behind. When combined with positioning and stacking contexts, it becomes a powerful tool for layered designs.