The z-index property puts components on different planes

To determine the overlapping of elements on each other in a page, CSS has z-index. But there are some things you should know before using it. This property is simple in principle.

There are many applications: boxes that can be dynamically displayed, overlapping tabs, zoom on images under the mouse ...

Syntax and principle

The z-index property takes for value an integer, positive or negative. Higher value shows an item over another, regardless of the display order. All that matters is the value relative to that of other elements.

So if a <div> has a z-index of 1, another will be displayed above and hide if it has a higher z-index, whatever it is 2 or 10.




The blue square has a z-index of 1, the red a z-index of 2 and the green a z-index of 3, it is displayed above the other two, even if it initially the green was displayed before the red and the red before the blue.

We can also dynamically change the visibility, as shown in the demonstration, with a JavaScript command.

If the square red square has the id "red" and the green square the id "green":

  z-index: 2;

  z-index: 3;
var r = document.getElementByid("red"); = 3;
var g = document.getElementById("green"); = 2;     

We now have the red square above the green:

Worth to know

The z-index is effective along with a position: absolute, fixed or relative. It is ignored with the static attribute that is the default. Therefore, always set the position attribute.

When not specified, items are displayed in order of appearance, the latter above the other.

When the z-index has a negative value, the object is hidden behind the container (in the demo, a fieldset). That with all browsers. It can therefore be used to display a lightbox dynamically.


To test the values of the CSS z-index on different browsers enter values in the form below, fields with corresponding figures in blue, red and green.
The figures have the position: absolute and are in a fieldset that position: relative.

Blue box Red box Green box

Enter values for each box and click Send.

© 2010-2012