Override CSS Z-Index Stacking Context

Q: Is there a way for an element to ignore the stack context of any of it’s parent elements and ask to be positioned relative to the original stack context of the page?

No, it’s not possible to transfer a positioned element between stacking contexts without repositioning the element in the DOM. You cannot even move an element to the root stacking context by using position: fixed or position: absolute (as you have observed, .red is being positioned relative to its parent, div:first-child because it creates a new stacking context).

That being said, given your HTML and CSS it should be trivial to just reassign the classes to the div elements instead, as shown in other answers and here so all your divs and spans participate in the root stacking context:

<div class="red"><span>Red</span></div>
<div class="green"><span>Green</span></div>
<div class="blue"><span>Blue</span></div>

But your situation probably isn’t as simple as it seems.

Leave a Comment