TannerRitchie Web Applications

Advanced Web Application Development in the GTHA

IE z-index bug and how to squash it …

A useful one to remember, because it’s cropped up in multiple sites recently.

IE (at least up to 9) does not handle z-index correctly. New *positioned* elements create new stacking contexts, beginning at zero, so you can run into counter-intuitive behaviour like the following:

<div id="positioned-div" style="position: relative;">
     <div id="inner-div" style='z-index: 1000'>
          Hello world
     </div>
</div>
<img src="i_am_still_higher.png" style="position: relative;"/>

Although “inner-div” has a high z-index, because it is inside “positioned div”, and the img is in a different context and *follows* “positioned-div” in the flow, img will always cover “inner-div” if the two overlap.

The fix is to assign a z-index to positioned-div that is higher than the image.

If this is complicated to grasp, a way to think of ‘positioned-div’ and the img as being as the same ‘level’ in the page tree, and they can therefore be positioned in their shared z-index context with CSS. The inner-div’s z-index only relates to it’s own parent, and has no relevance whatsoever to ‘cousin’ or ‘nephew’ elements.

A better way to visualize it might be to assign z-indexes how IE does it:

<div id="positioned-div" style="z-index: 1; position: relative;">
     <div id="inner-div" style='z-index: 1000'>
          Hello world
     </div>
</div>
<img src="i_am_still_higher.png" style="position: relative; z-index: 2"/>

Written this way, the z-index of ‘2’ will always be higher than a z-index of ‘1000’. However if ‘positioned-div’ is given a z-index of 3, it will be higher, as will ‘inner-div’ as one of its children.