Consider the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML</title>
<meta charset="utf-8" />
<style type="text/css">
h1 {
font-size: 2em;
font-family: Verdana;
font-weight: bold;
}
p {
border: 3px solid blue;
margin-top: -50px;
background-color: green;
color: white;
}
</style>
</head>
<body>
<h1>QUESTION</h1>
<p>The header text in the preceding h1 element is behind this
paragraph's text (as expected), but on top of this paragraph's
background and border (not expected).
</p>
</body>
</html>
See the example here: http://jsfiddle.net/ZKHc9/
Why isn’t the paragraph’s background and border rendered on top of the header like the content is?
Because the two elements are each in-flow, non-positioned, block-level elements in the same stacking context.
Two in-flow, non-positioned blocks aren’t strictly “above” or “below” each other — their contents and backgrounds stack separately.
Adding
position: relativewill make an element positioned (withz-index: auto) and place it above non-positioned elements in the same stacking context: it will be rendered at step 8 in the painting algorithm below.If you read the CSS2 spec’s Elaborate description of Stacking Contexts closely, you will see that this is correct behavior.
In-flow, non-positioned, block-level elements within the same stacking context first have all their backgrounds rendered, then all their contents. Their backgrounds are above positioned elements with a negative
z-indexand below everything else.The relevant steps in the painting algorithm:
Floated and positioned elements are always “atomic” — their backgrounds and contents will be rendered together in a single step (either step 3, 5, 8 or 9). But in-flow, non-positioned block elements within the same stacking context have all their backgrounds rendered (in step 4), then have all their contents rendered (in step 7).
In this case, for in-flow, non-positioned sibling elements H1 and P (H1 before P in the tree), step 4 renders the H1 background and then the P background, then step 7 renders the H1 content and then the P content.