Facebook Pixel

CSS Z-Index

When there are multiple overlapping elements, the z-index helps in deciding the order of their visibility. The element having the highest value of z-index is shown first, followed by the other elements.

Syntax

selector {
    position: relative | absolute | fixed | sticky;
    z-index: value;
}

z-index value can be:

  • Positive integer (e.g., 1, 10, 100) → Higher numbers appear above lower ones.
  • Negative integer (e.g., -1) → Pushes the element behind others.
  • Auto (default) → Follows the natural stacking order.

Note: The z-index property only works on positioned elements (relative, absolute, fixed, sticky).

Example:

<!DOCTYPE html>
<html>
 
<head>
    <title>CSS Z Index</title>
    <style>
        .container {
            position: relative;
        }
       
        .box1-box {
            position: relative;
            z-index: 1;
            border: 2px solid black;
            height: 100px;
            margin: 40px;
            background-color: aqua;
        }
       
        .box2-box {
            position: absolute;
            z-index: 3;
            background-color: rosybrown;
            height: 60px;
            width: 70%;
            left: 250px;
            top: 50px;
            border: 2px solid;
        }
       
        .box3-box {
            position: absolute;
            color: wheat;
            z-index: 2;
            background-color: rebeccapurple;
            width: 45%;
            left: 270px;
            top: 15px;
            height: 100px;
            border: 2px solid;
        }
    </style>
</head>
 
<body>
 
    <h1>CSS z-index</h1>
 
    <div class="container">
        <div class="box1-box">Box 1 (z-index: 1)</div>
        <div class="box2-box">Box 2 (z-index: 3)</div>
        <div class="box3-box">Box 3 (z-index: 2)</div>
    </div>
 
</body>
 
</html>

Output:

CSS Z index

When z-index isn’t used, the element defined last is shown on the topmost. Therefore, Box 3 would’ve been visible to us.

Default Stacking (Without z-index)

If you don’t specify a z-index, elements stack based on HTML order:

  • The element written later in the HTML appears on top.
  • In the above example, Box 3 would cover the others by default if no z-index was applied.