CSS - The z-index Property

The z-index property in CSS sets the z-order of an element, which determines the element's position in the stacking order of elements that overlap.

Elements with a higher z-index value will be displayed in front of elements with a lower z-index value.

The default value for z-index is auto, which means that the element will be positioned according to the order in which it appears in the HTML code.

To specify a z-index value, you can assign it a numeric value.

For example, z-index: 1; would position the element higher in the stacking order than an element with z-index: 0;.

Example with z-index:

Here's an example of using the z-index property to position two overlapping elements:

HTML:

<div class="box1">Box 1</div>
<div class="box2">Box 2</div>

CSS:

.box1 {
  position: absolute;
  z-index: 1; /* positioned higher in the stacking order */
  width: 100px;
  height: 100px;
  background-color: red;
}

.box2 {
  position: absolute;
  z-index: 0; /* positioned lower in the stacking order */
  width: 100px;
  height: 100px;
  background-color: blue;
}

In this example, the box1 element will be displayed in front of the box2 element because it has a higher z-index value. If you change the z-index value of box1 to 0 and box2 to 1, box2 will be on top of box1.

It is also worth noting that if both elements have the same z-index value, the element that appears last in the HTML code will be displayed in front of the other element.

Example without z-index:

Here's an example of positioning two overlapping elements without using the z-index property:

HTML:

<div class="box1">Box 1</div>
<div class="box2">Box 2</div>

CSS:

.box1 {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: red;
}

.box2 {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: blue;
}

In this example, the box2 element will be displayed behind the box1 element because it appears later in the HTML code. If you want to change the order, you can change the order of the elements in HTML.

<div class="box2">Box 2</div>
<div class="box1">Box 1</div>

In this case box2 will be on top of box1.

It's important to note that, you can also use other CSS properties like transform:translate() or opacity to change the order of the elements.

CSS Basics