Skip to content
DeveloperMemos

Understanding z-index in CSS

CSS, z-index, Frontend Development1 min read

CSS is a powerful tool when it comes to styling and laying out web pages. Among its many properties, z-index plays a crucial role in controlling the stacking order of positioned elements. In this article, we'll explore what z-index is, how it works, and provide practical examples to help you understand how to use it effectively in your web development projects.

Understanding z-index

The z-index property in CSS is used to define the stacking order of positioned elements. When elements overlap on a web page, the z-index property specifies which elements appear in front of others. By default, all elements have a z-index of auto, meaning they stack in the order they appear in the HTML markup.

How z-index works

When applying z-index to an element, a higher value will place the element in front of those with lower values. If two elements have the same parent, the one appearing later in the HTML code will be displayed in front. However, if the elements have different parents, the stacking order depends on the context.

Implementing z-index in CSS

Let's consider a simple example to demonstrate how z-index works. Suppose we have two overlapping <div> elements with different background colors, and we want to control their stacking order using z-index.

1<!DOCTYPE html>
2<html>
3<head>
4 <style>
5 .box {
6 position: absolute;
7 width: 200px;
8 height: 200px;
9 }
10
11 #box1 {
12 background-color: red;
13 top: 50px;
14 left: 50px;
15 z-index: 2;
16 }
17
18 #box2 {
19 background-color: blue;
20 top: 100px;
21 left: 100px;
22 z-index: 1;
23 }
24 </style>
25</head>
26<body>
27 <div class="box" id="box1"></div>
28 <div class="box" id="box2"></div>
29</body>
30</html>

In this example, box1 has a higher z-index value than box2, so it will appear in front of box2 despite their positions on the page.

Z-Index Example

Dealing with stacking contexts

It's important to note that the z-index property creates a new stacking context for the element and its children. This means that a child with a higher z-index value may still be obscured by its parent with a lower z-index if each has its own stacking context.

Summing Up

Now that you've grasped the basics of z-index, it's time to experiment with this property in your next web project and experience firsthand how it can influence the visual layout of your website!