Z-index

I made some real progress with z-index today. Something that seems simple but really isn't. Especially when browsers are involved.

Read this: for a great intro

Basically, there are 2 types:

Stacking contexts

This one is where 2 elements are not really related (or inside) to each other. When one has an index higher than the other it will always be on top. Even if a child of the element below had a higher index than the element above, it will always be below it as it has its own stacking context.

Stacking levels inside stacking context.

This one I found more peculiar. There are 7 levels inside the stacking level:

  • The borders and background of the current stacking context
  • Positioned descendants with negative z-index
  • Nonpositioned block-level descendants with no z-index property defined -- paragraphs, tables, lists, and so on
  • Floating descendants and their contents
  • Nonpositioned inline content
  • Positioned descendants with no z-index, z-index: auto, or z-index: 0
  • Positioned descendants with z-index greater than 0
  • Note: some older browser might swap the first 2 around.

What I found interesting on the above link is:

"Positioned elements paint on top of everything else if they don't have negative z-index. This means everything, including floats. "

I found this very useful. I had a footer that I used a negative top-margin on as I wanted the background image to look like part of the main content. The problem was that the footer was then on top of the main content so you couldn't click anything except the footer. By setting a position and z-index to the main content I was able to ensure that the content was always above the footer. Only the main content had a z-index set.

Great. What about if I wanted to make sure that any links in the footer DIV remain above the main content DIV? Easy, give the links a higher z-index than the main content. This kind of brings it back to regular stacking contexts.

What about IE?

On IE6 I had my footer absolutely positioned (for a reason beyond the scope of this). IE6 decides to take the positioning as a new stacking context (even with no z-index set) so as with my first example above, the links will never be at the top. Great. In this instance this is something I don't really need to do but is useful to note for further projects. Thanks to this page for this.

I'll add a link to the said project when its ready. I have tested most modern browsers to this date. For IE5 and 5.5 I'll do something simple.

There is also some more detailed information here

Last updated: July 08