Understanding the CSS z-index Property


When we think of CSS and web design, we generally think in two dimensions. After all, the screens we use to view websites display the page as a two-dimensional image. Two of the most common CSS properties, width and height, match that.

If you are new to CSS, you might not have heard about the z-index property. This property allows you to control the position of elements on the page in terms of layers, essentially adding a third dimension to the page.

Using z-index

The z-index of an element on the page is the layer that it is on, with the default being 0. As the z-index of an element increases, so does its layer.

Let's look at a quick example:

#box1 {
    background: #1144aa;
    width: 150px; height: 200px;
    position: absolute;
    left: 30px; top: 50px;
    z-index: 1;
#box2 {
    background: #ffd100;
    width: 200px; height: 20px;
    position: absolute;
    left: 20px; top: 75px;
    z-index: 20
#box3 {
    background: #ff6f00;
    width: 100px; height: 125px;
    position: absolute;
    left: 40px; top: 60px;
    z-index: 30;

With the sizes and positions of #box1, #box2 and #box3, there will be a space on the page that is occupied by all of these elements. By applying the z-index property to these boxes, we can define which one is on the top, which is in the middle, and which one is on the bottom, giving us something like this:

Now if we can imagine looking at the image from the side, we can visually see how the different layers are positioned on top of each other.

Try changing the z-index values for each of the elements, and you should be able to see how the resulting image changes. Try adding some more elements in there, and seeing what different combinations can be made.

Stay Updated

Did you enjoy this post? Don't miss a single post by getting free updates!

One Comment

  1. Antanas
    October 19, 2010

    A very good explanation of z-index!