Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing layer order of overlapping divs with content and background colors

Tags:

html

css

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:

weird layer order

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.

like image 684
Jamie Wong Avatar asked Nov 04 '22 21:11

Jamie Wong


1 Answers

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:

  • background of #foo
  • background of #bar
  • text content of #foo
  • text content of #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).

like image 189
bfavaretto Avatar answered Nov 08 '22 06:11

bfavaretto