0
0
CSSmarkup~5 mins

Z-index basics in CSS

Choose your learning style9 modes available
Introduction

Z-index helps decide which item appears on top when things overlap on a webpage.

You want a popup to appear above the page content.
You have overlapping images and want to control which one is visible on top.
You want a menu to appear above other page elements.
You want to fix a header so it stays visible above scrolling content.
You want to layer text over a background image clearly.
Syntax
CSS
selector {
  position: relative | absolute | fixed | sticky;
  z-index: number;
}

Z-index only works if the element has a position other than static.

Higher z-index numbers appear on top of lower ones.

Examples
This makes the div appear above elements with lower z-index.
CSS
div {
  position: relative;
  z-index: 10;
}
A popup with a high z-index stays on top of most elements.
CSS
.popup {
  position: fixed;
  z-index: 1000;
}
This background stays behind elements with higher z-index.
CSS
.background {
  position: absolute;
  z-index: 1;
}
Sample Program

The blue box overlaps the red box and appears on top because it has a higher z-index.

CSS
<style>
  .box1 {
    position: relative;
    width: 100px;
    height: 100px;
    background-color: red;
    z-index: 1;
  }
  .box2 {
    position: relative;
    width: 100px;
    height: 100px;
    background-color: blue;
    margin-top: -50px;
    margin-left: 50px;
    z-index: 2;
  }
</style>
<div class="box1"></div>
<div class="box2"></div>
OutputSuccess
Important Notes

If two elements have the same z-index, the one later in the HTML code appears on top.

Negative z-index values place elements behind the page background.

Summary

Z-index controls stacking order of overlapping elements.

Only works on positioned elements (not static).

Higher numbers appear on top.