Understanding z-index in CSS

understanding z index in css
10 November 2024

In the world of web design, the z-index property plays an important role in the arrangement and layering of elements.

The z-index feature specifically enables us to control which element appears in front and which element is placed behind during layering. This feature is particularly useful for working with modal overlays, pop-up windows, and overlapping content displays, which can be quite common.

Assume several elements are placed on top of each other; with the help of the z-index property, we can easily organize their display. A higher value for this property means that it will appear in front of other elements.

Setting a z-index may seem simple, but it should be noted that this property only works on elements that have a positioning context (like position: relative;, position: absolute;, or position: fixed;). Therefore, if it appears that z-index is not functioning, the first thing to check is the positioning of the element.

In the following, we will cover practical examples and explanations that can be applied in real-world scenarios.

 
  <style>
  .box1 {
    position: relative;
    z-index: 10;
    width: 100px;
    height: 100px;
    background-color: red;
  }

  .box2 {
    position: relative;
    z-index: 5;
    width: 100px;
    height: 100px;
    background-color: blue;
    margin-top: -50px;
    margin-left: 50px;
  }
  </style>

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

Line-by-Line Explanation:

.box1
The element is defined with the class box1.
position: relative;
The positioning of the element is relative to its default position.
z-index: 10;
The stacking order of this element equals one, meaning it sits above elements with a lower z-index.
background-color: red;
The background color of the element is red.
.box2
The second element is defined with a lower z-index.
margin-top: -50px;
This causes the second element to overlap the first, however, it remains below the first element due to its lower z-index.

FAQ

?

Why doesn't the z-index work on my element?

?

How can I use z-index in a real-world layout?