Given the following HTML:
<div class="foo">howdy howdy howdy how</div>
<div class="bar">Hello</div>
and the following CSS:
.foo {
background-color:green;
overflow:hidden;
height:.75em;
}
.bar {
color: white;
background-color: red;
margin-top: -10px;
width: 200px;
}
The layer order is something like this:
Here's the associated jsfiddle: http://jsfiddle.net/q3J8D/
I would expect the red background to be on top of the black text and don't understand why the black text is on top of the red background.
I can fix this problem using position: relative
, but I'm just curious.
Why is the black text on top of the red background?
I'm particularly looking for an official source/standard that explains this behaviour.
It took me a while to understand it, even after reading the spec multiple times, and BoltClock's answer to the linked question.
But it seems the explanation is simple: since these are two static (i.e. non-positioned), block-level elements inside the same stacking context (the root context), they are drawn in the following order:
#foo
#bar
#foo
#bar
Thus, the output we see in the question.
The paint order is dictated by an algorithm described in Appendix E of the CSS 2.1 spec. What is not in the appendix (but is mentioned here), is that the algorithm is applied recursively for each stacking context (not each element).
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