Jamie Wong
Jamie Wong

Reputation: 18350

Confusing layer order of overlapping divs with content and background colors

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.

Upvotes: 5

Views: 490

Answers (2)

bfavaretto
bfavaretto

Reputation: 71939

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).

Upvotes: 3

Tony318
Tony318

Reputation: 562

http://www.w3.org/TR/CSS21/visuren.html#z-index

"This example demonstrates the notion of transparency. The default behavior of the background is to allow boxes behind it to be visible. In the example, each box transparently overlays the boxes below it. This behavior can be overridden by using one of the existing background properties"

Upvotes: -1

Related Questions