DEV Community

Cover image for Why z-index Doesn’t Work (And How to Fix It)
Pawar Shivam
Pawar Shivam

Posted on

Why z-index Doesn’t Work (And How to Fix It)

=> Why z-index Is Not Working?

You write this:

.modal {
  position: absolute;
  z-index: 9999;
} 
Enter fullscreen mode Exit fullscreen mode

But still…

👉 It appears behind other elements.


=> The Real Problem

z-index only works within the same stacking context.

If elements are in different contexts → values don’t compare.


=> What Creates a Stacking Context

Many developers don’t know this.

These properties create new stacking contexts:

position: relative;
z-index: value;
opacity: < 1;
transform: translateZ(0);
filter: blur(0);
Enter fullscreen mode Exit fullscreen mode

=> Common Bug Example

.parent {
  position: relative;
  z-index: 1;
}

.child {
  position: absolute;
  z-index: 9999;
}
Enter fullscreen mode Exit fullscreen mode

If another element is outside this parent:

👉 It can still appear above .child


=> Why This Happens

Because .child is trapped inside .parent stacking context.

It cannot escape.


=> The Fix

Move element outside or remove stacking context:

.parent {
  position: static;
}
Enter fullscreen mode Exit fullscreen mode

Or:

👉 Move modal directly under <body>


=> Real UI Tip

For modals, dropdowns, overlays:

👉 Avoid deep nesting
👉 Render at top level


=> What Developers Often Miss

It’s not about increasing z-index.

It’s about understanding stacking context.


=> What Do You Think?

Have you ever tried z-index: 9999 and it still didn’t work?

Top comments (0)