Effect of z-index value to positioned elements

with help from Dave Hyatt 1

Through the entire tutorial, I will be using RP as short for relatively positioned element and AP for absolutely positioned element. I also assume that you know that z-index is the CSS property that defines where on z-axis that particular element is placed. z-axis' starting point is the monitor screen and it climbs up towards your eye.

CSS2.1 spec says that each positioned element defines stacking context for all its children if it has an integer z-index (i.e. non-auto). Further, if any of the child elements are positioned and has non-auto z-index, it defines new, internal stacking context. Nothing that is outside the stacking context can come between elements inside of the stacking context. If two elements have z-index:auto, the one that is later in the document order will be on the top.

You can imagine stacking contexts are solid boxes. No matter what you have or do inside of that box, its elements are constrained by those boxes and can not mix.

Lets look at this in the example. We have two RP, and one AP + one non-positioned paragraph in each of them. No z-index is applied, thus all elements take the default value of auto, which means: stack them as they come.

RP1: This is relatively positioned block

AP1: This is absolutely positioned block

Content between the RP blocks... Content between the RP blocks... Content between the RP blocks... Content between the RP blocks...

RP2: This is relatively positioned block

AP2: This is absolutely positioned block

Content after the second RP block... Content after the second RP block... Content after the second RP block... Content after the second RP block...

<div>RP1
<p>...</p>
	<div>AP1
	<p>...</p>
	</div>
</div>

<p>...</p>

<div>RP2
<p>...</p>
	<div>AP2
	<p>...</p>
	</div>
</div>

<p>...</p>

Correct overlapping order is (bottom to top):

Opera (up to 7.53) is erroneous here. It will render AP1 element above RP2 but below AP2.

Note: the original guide I published was erroneous in some significant parts, due to my miss-understanding of CSS2.1 spec. Within hours of linking this on WaSP Buzz, Dave Hyatt responded with clarification. I have updated this guide to reflect proper information.
For historical reasons, I have saved original pages - just add wrong/ to the URL of this page.
On March 18th, 2008, I have updated this tutorial with findings about IE8.