The z-index property

The z-index property sets which one will be on top in case several elements overlap each other.

Syntax

cssselector {
  z-index: number | auto;
}

The number must be an integer, positive or negative. It can be zero.

Values

Value Description
Number An integer specifies the order in which elements are overlapped: when elements are stacked on top of each other, the one with the greater z-index will be on top.
auto The overlaping order is built automatically: the element that is located below in the HTML code will be higher.

Default value: auto.

Example

In this example, the blocks will be overlaid on each other in the order they appear in the HTML code (z-index is not specified and will have the default value - auto). The first block will be at the very bottom (red), and the last block will be at the top (green):

html<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
css#div1 {
  position: absolute;
  top: 30px;
  left: 30px;
  width: 50px;
  height: 50px;
  background: red;
}
#div2 {
  position: absolute;
  top: 60px;
  left: 60px;
  width: 50px;
  height: 50px;
  background: blue;
}
#div3 {
  position: absolute;
  top: 90px;
  left: 90px;
  width: 50px;
  height: 50px;
  background: green;
}

Результат:

Example

Let's change the overlaping order by setting z-index. Red block - 3, blue - 2, green - 1. The overlaping order will be reversed (the block with z-index 3 will be on top):

html<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
css#div1 {
  position: absolute;
  top: 30px;
  left: 30px;
  width: 50px;
  height: 50px;
  background: red;
  z-index: 3;
}
#div2 {
  position: absolute;
  top: 60px;
  left: 60px;
  width: 50px;
  height: 50px;
  background: blue;
  z-index: 2;
}
#div3 {
  position: absolute;
  top: 90px;
  left: 90px;
  width: 50px;
  height: 50px;
  background: green;
  z-index: 1;
}

Результат: