0
0
CssDebug / FixBeginner · 3 min read

How to Fix z-index Not Working in CSS: Simple Solutions

The 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.

html
<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>
Output
Two overlapping squares appear with the blue box on top, ignoring the red box's z-index.
🔧

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.

html
<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>
Output
Two overlapping squares appear with the red box on top, respecting the z-index values.
🛡️

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: hidden can cut off child elements even if z-index is high.
  • Stacking context confusion: CSS properties like opacity, transform, and filter create new stacking contexts that affect z-index behavior.
  • Negative z-index: Elements with negative z-index can go behind the page background, making them invisible.

Key Takeaways

Set position to relative, absolute, or fixed for z-index to work.
z-index only affects positioned elements, not static ones.
Use browser DevTools to check stacking contexts and layering.
Avoid unnecessary stacking contexts to keep layering simple.
Watch out for overflow and CSS properties that create new stacking contexts.