Because z-index works only within the same stacking context.
π What’s Actually Happening
- Parent A (
z-index: 1) creates its own stacking context - Parent B (
z-index: 2) creates another stacking context - The child of Parent A, even with
z-index: 999, is restricted inside Parent A’s stacking context
So the browser compares:
- Parent A (z-index: 1) vs Parent B (z-index: 2)
π Since 2 > 1, Parent B is always on top, and children of A cannot escape their parent’s stacking context.
π§ͺ Example
.parentA {
position: relative;
z-index: 1;
}
.parentB {
position: relative;
z-index: 2;
}
.childA {
position: absolute;
z-index: 999;
}
Even with 999, .childA cannot overlap .parentB.
π§ Mental Model (Easy to Remember)
Think of stacking contexts as layers of glass:
- Parent A is on layer 1
- Parent B is on layer 2
- Child A can move only inside layer 1
- It cannot jump to layer 2
β How to Fix This
β Option 1: Move child outside Parent A
<body>
<div class="parentA"></div>
<div class="childA"></div> <!-- outside -->
</body>
β Option 2: Increase Parent A’s z-index
.parentA {
z-index: 3;
}
β Option 3: Use a portal (React)
Render the child into body to escape the stacking context.
π― Short Interview Answer
Because Parent A creates its own stacking context, its child’s z-index is scoped within that context.
Since Parent B’s stacking context has a higher z-index, it will always appear above Parent A and all of its children, regardless of how large the child’s z-index is.
β One-line summary
A child’s z-index cannot escape its parent’s stacking context.