Understanding z-index in CSS

understanding z index css stacking context example 2
10 November 2024

In CSS, the z-index property plays a crucial role in determining the stacking order of layers and the positioning of elements, especially when dealing with positioned elements. Here, I'll explain the usage and features of z-index in simple and conversational language so you can apply it correctly in real projects.

Let's assume there are several elements on a webpage that overlap each other, like when designing a floating menu. In such cases, z-index can help determine which element should appear on top. This property is particularly useful in complex layouts that are very visually intricate.

Let's delve a bit deeper. Whenever an element has a position property like relative or absolute, it can utilize z-index. However, it is important to note that z-index only applies to elements with a defined position, and if it is not specified, there might be issues such as a stacking context.

A stacking context is a concept that occurs when a parent element has a specific z-index. In this state, all child elements inherit that parent element, and they cannot extend beyond that scope unless they form a new stacking context.

To get a practical understanding of this concept, let’s look at an example of how z-index and stacking contexts can work together.


<style>
  .container {
    position: relative;
    z-index: 1;
  }
  .element1 {
    position: absolute;
    z-index: 3;
  }
  .element2 {
    position: absolute;
    z-index: 2;
  }
</style>
<div class="container">
  <div class="element1">Element 1</div>
  <div class="element2">Element 2</div>
</div>

<style>: Begins the definition of styles
.container: has a positioned relative and z-index: 1 to create a stacking context
.element1: has position: absolute and z-index: 3, placing it on top of element2
.element2: has position: absolute and z-index: 2, placing it below element1

FAQ

?

Why doesn't z-index work?

?

What is a stacking context?

?

How can I create a new stacking context?