How to Use CSS z-index?

CSS z-index can be confusing sometimes because it’s so simple yet when nested, can go so complex and numbers stop making sense.

the higher z-index it is closer to the viewer or it is having higher stacking order than other.

z-index will work in conjunction with a position property.

how to change the z-index using JavaScript?

well inside a style object there is a zIndex value that can be manipulated using JavaScript.

Basic html with nested divs

Lets just use 4 div element to understand the working of z-index.

the code structure look like this

<div class=z2> 
    <div class=z4>4</div>
    2
</div>
<div class=z1> 
    <div class=z3>3</div>
    1
</div>

Css classes with z-index

We’re using classes with numbering equal to their z-index values. So z1 class will have an index value of 1 and z2 will have an index of 2 and so on...

if we nest the elements the stacking context of the child will not exceed that of the parent value. So those with z-index 1 can not be over z-index 2 or higher.

Even though its child has an index of 3 which is greater than 2 but it can't get over its parent's z-index value.

body{
    padding:20px;
}
div{
    position:relative;
    width:50%;
    height:100px;
    float:left;
}
div>div{
    position:relative;
    padding:10px;
    width:50%;
    height:50px;
    margin:-10px 0 0 -10px }
.z1{
    z-index:1;
    background:hsl(0, 25%, 50%);
}
.z2{
    z-index:2;
    background:hsl(0, 50%, 50%);
}
.z3{
    z-index:3;
    background:hsl(0, 75%, 50%);
}
.z4{
    z-index:4;
    background:hsl(0, 100%, 50%);
}

Z-index and images

Edit Example

We can overlap multiple child images using z-index. For example, we can create a hover zoom effect on a tightly stacked grid structure.

the basic structure will have floating images like the below.

<div class="zindex-example">
<img src="http://imjignesh.com/img/400" />
<img src="http://imjignesh.com/img/400" />
<img src="http://imjignesh.com/img/400" />
<img src="http://imjignesh.com/img/400" />
</div>

Manipulate z-index on hover

The image hover state will have a transform property but since all the images are using the same z index the zoomed image overlapping would not create the expected result.

body{overflow:hidden;}
.zindex-example img{
    max-width:50%;
    width:50%;
    height:auto;
    position:relative;
    z-index:1;
    float:left;
}
.zindex-example img:hover{
    transform:scale(1.2);
}

Edit Example

That's why we use the z-index on the hover state to show the zoomed image on top of its siblings.

Edit Example

Small z-index addition on hover state:

/* before */
.zindex-example img:hover{
    transform:scale(1.2);
}
/* after */
.zindex-example img:hover{
    transform:scale(1.2);
    z-index:2;
}