CSS Layout

CSS Z-index

The CSS Z-index property controls the stacking order of positioned elements on a webpage.

When two or more elements overlap, the element with the higher z-index value appears in front of the others.

Think of z-index as layers stacked on top of each other:

  • Higher z-index = Closer to the user
  • Lower z-index = Further behind

Z-index is commonly used for:

  • Navigation menus
  • Popups and modals
  • Tooltips
  • Dropdown menus
  • Floating buttons

Syntax

CSS Z-index Syntax

css

selector {
    z-index: value;
}

CSS Z-index Example

css

.box {
    position: absolute;
    z-index: 10;
}

This places the element above elements with lower z-index values.

Attributes

PropertyDescriptionExample
z-indexSets stacking orderz-index: 5;
z-indexHigher value appears in frontz-index: 100;
z-indexLower value appears behindz-index: 1;
z-indexNegative stacking orderz-index: -1;
z-indexDefault stacking orderz-index: auto;

Example

CSS Z-index Complete Example

html

<!DOCTYPE html>
<html>
<head>
    <title>CSS Z-index Example</title>
    <style>
        .container {
            position: relative;
            height: 250px;
        }
        .box1 {
            position: absolute;
            top: 20px;
            left: 20px;
            width: 200px;
            height: 150px;
            background-color: lightblue;
            z-index: 1;
        }
        .box2 {
            position: absolute;
            top: 60px;
            left: 80px;
            width: 200px;
            height: 150px;
            background-color: orange;
            z-index: 2;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="box1">Box 1 (z-index: 1)</div>
        <div class="box2">Box 2 (z-index: 2)</div>
    </div>
</body>
</html>

Output

Browser Output

css

Two boxes will overlap
The orange box (z-index: 2) will appear in front
The blue box (z-index: 1) will appear behind
The higher z-index value determines which element is visible on top

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE
YesYesYesYesYesYes

Notes

  • z-index only works on positioned elements: position: relative, position: absolute, position: fixed, and position: sticky.
  • Elements with higher z-index values appear above lower values.
  • Negative z-index values can place elements behind others.
  • z-index: auto uses the default stacking order.
  • Avoid extremely large z-index values unless necessary.

Common Layering Example

ElementTypical Z-index
Page Content1
Sticky Header100
Dropdown Menu1000
Modal Window10000
Tooltip100000

Conclusion

The CSS Z-index property is essential for controlling the stacking order of overlapping elements. By using z-index with positioned elements, you can create dropdowns, modals, tooltips, and other layered interface components that appear correctly above or below other content.