How to Fix z-index Not Working in CSS: Simple Solutions
z-index property only works on elements with a position value other than static. To fix z-index not working, ensure the element has position: relative, absolute, or fixed set, so stacking order applies correctly.Why This Happens
The z-index property controls the stack order of elements, but it only works on elements that have a position value other than the default static. If you set z-index on a statically positioned element, the browser ignores it, so the layering won't change as expected.
<style>
.box1 {
width: 100px;
height: 100px;
background-color: red;
z-index: 10; /* This won't work because position is static */
}
.box2 {
width: 100px;
height: 100px;
background-color: blue;
margin-top: -50px;
}
</style>
<div class="box1"></div>
<div class="box2"></div>The Fix
To fix the issue, add position: relative (or absolute, fixed) to the element with z-index. This activates stacking context and makes z-index work as expected.
<style>
.box1 {
width: 100px;
height: 100px;
background-color: red;
position: relative; /* Added position */
z-index: 10;
}
.box2 {
width: 100px;
height: 100px;
background-color: blue;
margin-top: -50px;
position: relative; /* Also positioned to compare layering */
z-index: 5;
}
</style>
<div class="box1"></div>
<div class="box2"></div>Prevention
Always set a position value other than static when using z-index. Use position: relative for simple layering without removing elements from the document flow. Avoid unnecessary stacking contexts by not overusing position and z-index. Use browser DevTools to inspect stacking contexts and layering issues.
Related Errors
Other common layering issues include:
- Overflow hidden clipping: Parent containers with
overflow: hiddencan cut off child elements even ifz-indexis high. - Stacking context confusion: CSS properties like
opacity,transform, andfiltercreate new stacking contexts that affectz-indexbehavior. - Negative z-index: Elements with negative
z-indexcan go behind the page background, making them invisible.