CSS z-index property

z-index property

The CSS z-index property specifies the layering or stacking of positioned elements. In other words, z-index value decides which layer has to be shown in front and in back. The element having higher z-index value will be shown in front as compared to elements having lower z-index values.

z-index works only for elements having position absolute, relative, fixed or sticky.

The syntax of z-index property is shown below:

z-index:number|auto|inherit|initial
div{
    position:absolute;
    top:40px;
    left:50px;
    z-index:2;
}

z-index property values

z-index property takes the following values on the elements.

auto

It is the default value. It sets the stack order equal to its parent.

number

It sets the stack order of the element. The higher number will make an element to show it in front.

initial

Set it to its default value.

inherit

Inherit this property from its parent element.

Let us now write a small code to understand the z-index property of CSS.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Example of CSS z-index property</title>
    <style>
        div {
            border: 2px solid black;
            width: 200px;
            height: 200px;
            color:white;
        }

        div.box1 {
            top: 100px;
            position: absolute;
            background: #00ff55;
            z-index: 1;
        }
        div.box2 {
            top: 70px;
            left:100px;
            position: absolute;
            background: #048a04;
            z-index: 4;
        }
        div.box3 {
            top: 100px;
            left:230px;
            position: absolute;
            background: #d34605;
            z-index: 3;
        }
        div.box4 {
            top: 140px;
            left:130px;
            position: absolute;
            background: #b1075c;
            z-index: 5;
        }
    </style>
</head>
<body>
    <h3>Four boxes with different z index values</h3>
    <div class="box1">z-index=1</div>
    <div class="box2">z-index=4</div>
    <div class="box3">z-index=3</div>
    <div class="box4">z-index=5</div>
</body>
</html>
z-index, www.programmingtutorial.in
www.programmingtutorial.in