Find out how elements stack and start using low z-index values

This article was first published on tjkdesign.com (02-26-2008).

A few weeks ago I was called to fix a layout issue. A modal window would not show, so I used Firebug to style it using position:relative;z-index:9999 (because I know people use crazy values). It still didn’t work; so I tried 999999, but that didn’t help either.

It turned out that a wrapper had a z-index value of 1000000! I’m not kidding, 1000000 (one million) no less… But not only that, I couldn’t find the reason why this wrapper was styled with a z-index to begin with…

So I hope this article, along with this “z-index tool”, will help you better understand what stacking context means and how things work when it comes to z-index.

(Note: when using the “z-index tool”, start out by playing just with the radio buttons to understand where stacking starts.)

z-index tool

The golden rules

For a positioned box, the z-index property specifies:

  1. The stack level of the box in the current stacking context.
  2. Whether the box establishes a local stacking context.

If there is no z-index specified, elements are stacked in the following order (from back to front):

  1. boxes in the normal flow, according to the sequence in the source code
  2. floating boxes
  3. positioned boxes, according to the sequence in the source code

Heads up

A relatively positioned element without a z-index set does not establish a stacking context, but…

A common IE bug, often seen in drop-down menus, is that any relatively positioned element that has haslayout set to true establishes a stacking context.
One may visualize this bug by setting [A] and [B] to position:relative, while [a] gets position:relative; z-index:1.
Now, dragging [A] under [B] hides [a] - in Internet Explorer, that is. Any positioned child with a z-index is caught by this wrong stacking context of its parent.http://www.satzansatz.de/css.html

Further reading