CSS2: z-index

Here is a post I wrote on webmasterworld.com to explain how z-index works.

z-index goes hand-in-hand with the local stacking context. What is a stacking context? Whenever you specify a z-index, you create a new stacking context. Here's an example:

CSS:

body {
  margin: 0;
  padding: 0;
}

/* generic style */
div.tile {
  position: absolute;
  border: 1px solid black;
  background: white;
  width: 4em;
  height: 4em;
}

/* box One */
.a {
  top: 0;
  left: 0;
}

/* box Two */
.b {
  top: 1em;
  left: 1em;
}

/* box Three */
.c {
  top: 2em;
  left: 2em;
  z-index: -1;
}

/* box Four */
.d {
  top: 3em;
  left: 3em;
} 

/* box Five */
.e {
  top: 4em;
  left: 4em;
}

HTML:

<div style="position: absolute; z-index: 0;">
  <div class="tile a">One</div>
  <div class="tile b">Two</div>
  <div class="tile c">Three</div>
  <div class="tile d">Four</div>
</div>

<div class="tile e">Five</div>

So here we have three stacking contexts, the root of the document (<html>), the plain div, and box Three (.c).

When you specify a z-index, that z-index is the offset relative to the current stacking level. (So setting the z-index to 500 isn't going to place the element in front of a z-index of 5, necessarily.)

When the z-index on the plain div is 0, boxes One, Two, Four, and Five stack on top of each other sucessively. Since box Three has a negative z-index it is rendered behind boxes One, Two, and Four, and Five. The stacking order from bottom to top is: 3, 1, 2, 4, 5

Example:

One
Two
Three
Four

Five

If you give the z-index on the plain div a 1, boxes One, Two, Three and Four are rendered in front of box Five (change the position and size of box five, go ahead), but box Three is rendered behind boxes One, Two, and Four, due to its negative z-index. The stacking order from back to front is: 5, 3, 1, 2, 4

Example:

One
Two
Three
Four

Five

If you remove the z-index on the plain div, boxes One, Two, Four, and Five are rendered sucessively on top of each other, and box Three is rendered behind the root stacking context (the html element) and cannot be seen. The stacking order from bottom to top is: 3, root, 1, 2, 4, 5)

Example:

One
Two
Three
Four

Five

Further Reading

CSS2 Section 9.9: Layered presentation