Understanding z-index in CSS

css z index tutorial
10 November 2024

When discussing CSS and web design, one of the common topics that comes up is the concept of z-index. z-index allows us to control the stacking order of elements on web pages, creating a fully customizable definition. However, at times this topic can be quite confusing, particularly when dealing with non-scrollable browsers. We should take a closer look at this concept to understand how we can make the best use of it.

First of all, we must know that z-index only works for positioned elements. This means elements that are defined with position: relative; or position: absolute;. When several positioned elements are present, the z-index of each can be determined in ascending numerical order.

If two elements overlap, the element with the higher z-index will layer over the other element. For instance, a z-index of 2 is greater than 1, and for this reason, the element with z-index: 2 will stack over the element with z-index: 1.

However, issues can arise in cases where no z-index is defined for certain elements. In this situation, the browser will typically consider the stacking order as zero and order the layers in a cascading manner in the DOM.

Practical Example of z-index Code in CSS


    <div class="container">
<div class="box" style="position: relative; z-index: 1;">Box 1</div>
<div class="box" style="position: relative; z-index: 3;">Box 2</div>
<div class="box" style="position: relative; z-index: 2;">Box 3</div>
</div>

Line-by-line Code Explanation:

<div class="container">
Here we create a div with the class container, which serves as the container for other elements.

<div class="box" style="position: relative; z-index: 1;">Box 1</div>
This element is a box with a relative position and z-index: 1, which means it will be placed behind elements with a higher z-index.

<div class="box" style="position: relative; z-index: 3;">Box 2</div>
This element has a higher z-index, and will therefore lay over all elements with a lower z-index.

<div class="box" style="position: relative; z-index: 2;">Box 3</div>
This element with z-index: 2 is placed between Box 1 and Box 2.

</div>
Closing tag of the container, which encapsulates all the boxes.

FAQ

?

How can I ensure that an element is placed above all other elements?

?

Why doesn't z-index work for some elements?