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.)
The golden rules
- A box is at the same stack level as its parent’s unless it is given a different stack level through the
z-indexproperty. z-indexapplies only to objects that have thepositionproperty set torelative,fixedorabsolute.- Assigning an opacity value less than 1 to a positioned element implicitly creates a stacking context, just like adding a
z-indexvalue.
For a positioned box, the z-index property specifies:
- The stack level of the box in the current stacking context.
- 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):
- boxes in the normal flow, according to the sequence in the source code
- floating boxes
- boxes for wich the computed display value is
inline,inline-block, orinline-table - positioned boxes and boxes with a opacity < 1, according to the sequence in the source code
Heads up
In WebKit, styling a box with position:fixed or -webkit-overflow-scrolling:touch implicitly creates a stacking context, just like adding a z-index value.
Also, be aware of these CSS3 “triggers”:
- transform != none
- transform-style: preserve-3d
- filter != none
- clip-path, mask
Lastly, even though a relatively positioned element without a z-index set does not establish a stacking context…
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] toposition:relative, while [a] getsposition: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