#parent {
position: relative;
background: red;
width: 100px;
height: 100px;
z-index: 1;
}
#child {
position: absolute;
top: 50px;
left: 50px;
z-index: -1;
transform: translateX(20px);
}
<div id="parent">
<p>
qqq
</p>
<div id="child" >
test
</div>
</div>
If I don't set the parent's z-index to 1, the child's z-index will let it under the parent. But when I set the parent's z-index to 1 (or any number higher than 0), the child's z-index won't work!
Why is this happening?
By default, all background colour goes behind the text. the z-index default is auto which states "Sets the stack order equal to its parents". However, using z-index on the child will move it out of the natural stack order and place it behind the background. If you change the parent to also have a Z-Index then it will rejoin the stack and the background colour will again appear behind the text.
Both parent and child are set to AUTO. Both in the same stack.
#parent {
position: absolute;
background: red;
width: 100px;
height: 100px;
}
#child {
position: absolute;
top: 50px;
left: 50px;
transform: translateX(20px);
}
<div id="parent">
<div>
qqq
</div>
<div id="child" >
test
</div>
</div>
Child set to z-index -1 now it is not in the same stack as the parent
#parent {
position: absolute;
background: red;
width: 100px;
height: 100px;
}
#child {
position: absolute;
top: 50px;
left: 50px;
z-index: -1;
transform: translateX(20px);
}
<div id="parent">
<div>
qqq
</div>
<div id="child" >
test
</div>
</div>
Child set to z-index -1 and parent set to z-index 1 making them both in the same stack so the background color gets put behind both elements.
#parent {
position: absolute;
background: red;
width: 100px;
height: 100px;
z-index: 1;
}
#child {
position: absolute;
top: 50px;
left: 50px;
z-index: -1;
transform: translateX(20px);
}
<div id="parent">
<div>
qqq
</div>
<div id="child" >
test
</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