I'm trying to grasp why the blue divs in this example are not always on top? i.e. how come red div #2 is on top of blue child 1.
body {
padding: 30px;
}
.red1 {
position: absolute;
z-index: 1;
width: 400px;
height: 200px;
background: red;
}
.red2 {
position: absolute;
z-index: 1;
width: 400px;
height: 200px;
top: 250px;
background: red;
}
.blue {
z-index: 9;
padding: 10px;
text-align: center;
color: white;
text-transform: uppercase;
position: absolute;
top: 100px;
left: 100px;
width: 150px;
height: 130px;
background: blue;
}
<div class="red1">
<div class="blue">
blue child 1
</div>
</div>
<div class="red2">
<div class="blue">
blue child 2
</div>
</div>
FIDDLE
Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).
z-index is relative.
If several elements share the same z-index value (i.e., they are placed on the same layer), stacking rules explained in the section Stacking without the z-index property apply.
Yes: use position:relative; z-index:10 . z-index has no effect for position:static (the default).
Because .red1 and .red2 form different stacking contexts.
The elements within one stacking context do not participate along with the elements within another stacking context.
If you give .red2 a z-index: -1, you will get the behavior you expect (demo).
That's because .red1 and .red2 are both absolutely positioned with no positioned ancestor. This means the root element is their immediate ancestor, and the root element forms a stacking context.
More details here:
z-index propertybody {
padding: 30px;
}
.red1 {
position: absolute;
z-index: 1;
width: 400px;
height: 200px;
background: red;
}
.red2 {
position: absolute;
z-index: 1;
width: 400px;
height: 200px;
top: 250px;
background: red;
}
.blue {
z-index: 9;
padding: 10px;
text-align: center;
color: white;
text-transform: uppercase;
position: absolute;
top: 100px;
left: 100px;
width: 150px;
height: 130px;
background: blue;
}
<div class="red2">
<div class="blue">
blue child 2
</div>
</div>
<div class="red1">
<div class="blue">
blue child 1
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With