Using CSS z-index property

The CSS z-index property is used along with the position property to create an effect of layers. You can specify which element should come on top and which element should come at the bottom.

Syntax

selector {
    z-index: value;
}

Possible Values

Value Description
auto Default value. Stack order is inherited from parent
integer Sets the stack order (higher values appear on top)

Example: Layering Elements

The following example demonstrates how to use z-index to control which element appears on top −

<!DOCTYPE html>
<html>
<head>
<style>
    .layer-blue {
        background-color: blue;
        width: 300px;
        height: 100px;
        position: absolute;
        top: 10px;
        left: 80px;
        z-index: 2;
    }
    
    .layer-gray {
        background-color: gray;
        width: 300px;
        height: 100px;
        position: absolute;
        top: 40px;
        left: 35px;
        z-index: 1;
    }
    
    .layer-yellow {
        background-color: yellow;
        width: 300px;
        height: 100px;
        position: absolute;
        top: 70px;
        left: 120px;
        z-index: 3;
    }
</style>
</head>
<body>
    <div class="layer-blue"></div>
    <div class="layer-gray"></div>
    <div class="layer-yellow"></div>
</body>
</html>
Three overlapping colored boxes appear: yellow box on top (z-index: 3), blue box in middle (z-index: 2), and gray box at the bottom (z-index: 1).

Key Points

  • The z-index property only works on positioned elements (position: relative, absolute, fixed, or sticky)
  • Higher z-index values appear on top of lower values
  • Elements with the same z-index are stacked according to their order in the HTML

Conclusion

The z-index property provides precise control over element layering in CSS. Remember that it only affects positioned elements and higher values create a stacking order that places elements on top.

Updated on: 2026-03-15T11:25:17+05:30

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements