The Concept of z-index in CSS

understanding z index css
10 November 2024

Hello friends! Today we want to talk about an interesting and popular concept in the world of CSS: z-index. It is certainly worth mentioning that sometimes you want to place multiple layers of content on top of each other, and the question arises about how to change this layering order. Here, z-index comes into play.

One thing to note is that z-index is actually a number that is related to HTML elements and specifies how each element relates to others in which layer they are located. Basically, whenever the z-index value of an element is higher, that element will be positioned above the other elements.

However, you should remember that z-index only works on positioned elements. That is, elements that are defined with position: relative, absolute, or fixed. To use z-index, you must first define the position for the element.

A small but important point is that the way of defining z-index should be done carefully. If you want two elements that are not on the same surface (for example, one inside a parent and the other in another parent) to overlap with z-index, you might get unexpected results.

Example Code for z-index


<!-- HTML Structure -->
<div class="container">
  <div class="box1">Box 1</div>
  <div class="box2">Box 2</div>
</div>

<!-- CSS Code -->
.container {
  position: relative;
  width: 200px;
  height: 200px;
}
.box1, .box2 {
  position: absolute;
  width: 100px;
  height: 100px;
}
.box1 {
  background-color: red;
  z-index: 1;
  top: 0;
  left: 0;
}
.box2 {
  background-color: blue;
  z-index: 2;
  top: 50px;
  left: 50px;
}

Line by Line Explanation of the Code

<div class="container">
This element acts as a parent for the next two elements and creates a context.
<div class="box1">Box 1</div>
This is an element with the class box1 and a red background color.
<div class="box2">Box 2</div>
This element has the class box2 and a blue background color, which will be placed above box1.
.container { position: relative; }
This defines the parent position relative to which z-index is used.
.box1, .box2 { position: absolute; }
Both elements are coded to have z-index applied.
.box1 { z-index: 1; }
z-index for box1 is set to 1, meaning it will be below box2.
.box2 { z-index: 2; }
z-index for box2 is set to 2, meaning it will be on top of box1.

FAQ

?

Why does z-index sometimes not work?

?

How can I avoid creating unwanted stacking contexts?