CSS z-index overridden by element order on page

cssz-index

I've been battling with CSS z-index in IE7 foe a couple of hours now, maybe you can help!

I have a absolutely positioned div, appearing above its parent div, which is great. But – it appears under later divs that are siblings to its parent.

That seems like quite bizarre behavour, like the z-index only applies to the local scope of each div or something.

How can I set things up so that when I set an element to have a greater z-index than any other element on the page, it will appear on top regardless?

Here's my test page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>test</title>
</head>
<body>
<div style="position: relative; z-index: 0">
    div1
    <div style="position: relative; z-index: 0">
        div2
    </div>
    <div style="color: red; background-color: #ffffff; position: absolute; z-index: 2">
        div3
    </div>
</div>
<div style="position: relative; z-index: 0">
    div1
    <div style="position: relative; z-index: 0">
        div2
    </div>
    <div style="color: red; background-color: #ffffff; position: absolute; z-index: 2">
        div3
    </div>
</div>
<div style="position: relative; z-index: 0">
    div1
    <div style="position: relative; z-index: 0">
        div2
    </div>
    <div style="color: red; background-color: #ffffff; position: absolute; z-index: 2">
        div3
    </div>
</div>
</body>
</html>

Best Answer

IE has a major z-index bug:

In Internet Explorer positioned elements generate a new stacking context, starting with a z-index value of 0. Therefore z-index doesn't work correctly.

You could try to change z-indexes, but if you want both elements to appear, you might have to pull them out of their ancestor structure and make them top-level DOM elements.