z-index needs to use with position:relative or position:absolute

By Nethru Limited (www.nethru.com)

CSS

Why my z-index is not working? Because z-index only works on positioned elements (position:absolute, position:relative or position:fixed).

z-index is a CSS property for specifying the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order.
(For details, please visit w3schools.com).

If you found that the element with z-index does not work, the most common reason is the element does not have position set. Just set position:absolute, position:relative or position:fixed can resolve the problem. But you may found another problem, the behaviour in IE6, IE7 and Firefox are different. Let’s look at the following example.

And below is the HTML code.

<div style="z-index: 1; background-color: #0f0; position: absolute; top: 20px; left: 20px; width: 120px; height: 120px;"></div>
<div style="background-color: #00f; position: relative; width: 180px; height: 180px;">
  <div style="z-index: 2; background-color: #f00; position: absolute; top: 40px; left: 40px; width: 120px; height: 120px;"></div>
</div>

In IE6, IE7, you will see green, red, blue in top to bottom order. But in Firefox, Chrome and IE8, IE9, you will see red, green, blue order.

The problem comes from the red node, it is a child node of the blue node, and the blue node does not have z-index set.

According to the W3C standard, only positioned elements with z-index set and the value is not equal to “auto” will generate a new stacking context. Since the blue node does not have z-index set, it does not generate another stacking context for itself and its child nodes, so the red and green nodes are on the same stacking context and the red node is over the green node. This means the behaviour in Firefox, Chrome and IE8, IE9 is following the W3C standard.

However in IE6, IE7, it seems every positioned elements will create a new stacking context, no matter whether or what value is set for the z-index. Since the red node is a child of the blue node, and the blue node is under the green node, so the red node can just cover the blue node but under the green node, although it has the largest value of z-index among the three nodes.

Therefore, if you use z-index, be careful with the different behaviours in IE6, IE7.

Leave a Reply

Your email address will not be published. Required fields are marked *