htmlcssz-index

Are z-index of child elements local to the parent?


Okay so I have this test setup in my html

<div style="position:absolute;left:0px;top:0px;z-index:1;width:200px;height:200px;background-color:red;">
  <div style="position:absolute;left:0px;top:0px;z-index:3;width:50px;height:50px;background-color:green;"></div>
</div>
<div style="position:absolute;left:0px;top:0px;z-index:2;width:100px;height:100px;background-color:blue"></div>

Where I want the blue div to render in front of the red div, but I want the green child div of red to render in front of blue.

Looking at that code it seems it should work if z-index was global, but it seems to be local to the parent element, as the blue renders above red, but the green doesn't render on top unless I move the green div up out of the parent?

<div style="position:absolute;left:0px;top:0px;z-index:1;width:200px;height:200px;background-color:red;"></div>
<div style="position:absolute;left:0px;top:0px;z-index:3;width:50px;height:50px;background-color:green;"></div>
<div style="position:absolute;left:0px;top:0px;z-index:2;width:100px;height:100px;background-color:blue"></div>

How can I use "global z-indexes", if they exist? It is vital to my actual project that it works this way.


Solution

  • Z-indices are always local, or relative, to the closest positioned ancestor (in this case the parent). There is no global z-index property in CSS.

    You will have to move the green div out of its parent.