I'm perplexed by the behavior of stacking order when applying an opacity level other than 1 to a child element. It seems that setting any other opacity value causes the child element to always dominate its siblings in terms of stacking.
.element {
width: 500px;
height: 100px;
background: orangered;
}
.child {
height: 150px;
width: 100px;
background: grey;
opacity: 0.5;
z-index: 1;
}
.sibling {
width: 400px;
height: 100px;
background: skyblue;
z-index: 2;
}
<div class="element">
<div class="child"></div>
</div>
<div class="sibling"></div>
If the opacity property is removed (or set back to 1) for the .child
element, it behaves as expected and stacks behind the .sibling
element. However, any non-1 opacity values seem to alter this stacking relationship. This leads me to think that .element
might be establishing a stacking context, although upon review, I couldn't find evidence of this based on MDN's criteria.
The CSS standard doesn't offer much insight into this:
It mentions that an element with less than full opacity creates a new stacking context, but beyond that, there isn't guidance on how opacity impacts stacking orders within elements. My example involving
.child
suggests that while it may create a stack context internally, its position relative to surrounding elements remains consistent. Further tests usingdisplay: flow-root
confirm this behavior even without the opacity adjustment.
So what exactly is happening here?