In my previous post I was exploring the effect containing blocks have on absolutely positioned elements. I did say that containing blocks have an effect on z-index as well. The effect is that elements with a higher z-index but within a containing block are rendered behind an element with a smaller z-index.

It turns out that the effect is probably a bug and that it only happens in older versions of IE, that is IE6 and IE7, IE8 renders correctly. I know its a complete pain to develop for old versions of any browser, I still have that scars from developing for Netscape 4 however a professional developer cannot pick and choose which browsers to support and like it or not my clients demand that I can produce sites that render in IE6 and 7.

This is how the problem shows up. I reused the HTML from the previous post. This time I have a red div that has a z-index of 2 and a green div with a z-index of 1. Like this

<html> 
 <head> 
  <title>Positioning</title> 
  <style type="text/css"> 
    .container
    {
    	background-color: Blue;
    	position: relative;
    	padding: 5px;
    	margin: 0px;
    }
    .contained_p
    {
    	background-color: Red;
    	position: absolute;
    	top: 10px;
    	left: 10px;
    	margin: 0px;
    	z-index: 2;
    }
    .free_p
    {
    	background-color: Green;
    	position: absolute;
    	top: 355px;
    	left: 10px;
    	margin: 0px;
    	z-index: 1;
    }
  </style> 
 </head> 
 <body> 
  <p class="free_p">should be<br />behind</p>
  <p>paragraph 1</p> 
  <p>paragraph 2</p> 
  <p>paragraph 3</p> 
  <p>paragraph 4</p> 
  <p>paragraph 5</p> 
  <p>paragraph 6</p> 
  <p>paragraph 7</p> 
  <p>paragraph 8</p> 
  <p>paragraph 9</p> 
  <div class="container">Container 
   <p class="contained_p">should be<br />on top</p> 
  </div> 
 </body> 
</html>

The red div should be on top as it has the highest z-index however in IE6 and IE7 it looks like this

z-ie7

it appears that the z-index value comparison is only valid for elements that are in the same containing block in IE6 and IE7

In IE8, Firefox and Opera it renders correctly like this

z-ie8

Its pretty easy to see the effect when the HTML has been stripped back, however in the middle of a complex page that has some weird positioning or z-index problem then this can be very difficult to track down.