I'm trying to get a div to show as a partial background below the inline content of is containing div but above the background of its container. If I set the z-index of just the partial background to -1 it appears behind the background. But if i set the containing divs z-index to 1 while the contained div's z-index is -1 it displays as desired.
Can someone explain to me why this is and if this is a reliable method or not?
.container {
position: relative;
width: 80%;
height: 18px;
padding: 6px 10px;
background: #666;
z-index: 1;
}
.partialbg {
position: absolute;
left: 0px;
top: 0px;
height: 30px;
width: 80%;
background: #0CC;
z-index: -1;
}
<div class="container">Text here
<div class="partialbg"></div>
</div>
No, z-index cannot be applied to a background image.
In order for z-index to have any effect at all, it needs to be applied to a positioned element, that means, an element with position relative , absolute , fixed , or sticky . If you don't apply a z-index , the elements will be stacked in the order they are written in the HTML. Check this example: HTML.
Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).
The reason this is occurring, is because there is a child and a parent. If you set a z-index
on the parent, the child is going to be the same, since the z-index
is stacked.
Thus, by setting a z-index
of 1
on the parent, the child is now also 1
.
It is systematically impossible for the child to be behind the parent, as that doesn't make any sense. However, the text is a sibling of the child. By setting a z-index
of -1
on the child, there is essentially no effect between the child and the parent, however since the sibling is effected, the child now goes behind the sibling.
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