The z-index property in CSS (Cascading Style Sheets) is a powerful tool for controlling the stacking order of elements on a web page. It determines which elements appear in front of or behind other elements. Understanding how to use the z-index property effectively can help you manage overlapping content and create complex layouts. In this guide, we’ll explore how the z-index property works and provide examples of its application.
What is Z-Index?
The z-index property specifies the stack level of an element. Elements with a higher z-index value will appear in front of elements with a lower z-index value. The z-index property only works on elements that have a position value other than static (i.e., relative, absolute, fixed, or sticky).
Basic Usage:
HTML Example:
<div class="box box1">Box 1</div>
<div class="box box2">Box 2</div>
<div class="box box3">Box 3</div>
CSS Example:
.box {
width: 100px;
height: 100px;
position: absolute;
color: white;
font-size: 20px;
display: flex;
align-items: center;
justify-content: center;
}
.box1 {
background-color: red;
top: 50px;
left: 50px;
z-index: 1;
}
.box2 {
background-color: green;
top: 100px;
left: 100px;
z-index: 2; /* Higher stack level */
}
.box3 {
background-color: blue;
top: 150px;
left: 150px;
z-index: 3; /* Highest stack level */
}
How Z-Index Works:
In the example above:
Box 1(red) has az-indexof 1.Box 2(green) has az-indexof 2.Box 3(blue) has az-indexof 3.
Because Box 3 has the highest z-index, it will appear in front of Box 2, which in turn appears in front of Box 1.
Z-Index and Positioning:
As mentioned earlier, the z-index property only applies to positioned elements (relative, absolute, fixed, sticky). If an element is not positioned, the z-index property will have no effect.
Negative Z-Index Values:
You can also use negative z-index values to place an element behind others.
Example:
.box4 {
background-color: yellow;
top: 200px;
left: 200px;
z-index: -1; /* Below all other elements */
}
HTML:
<div class="box box4">Box 4</div>
In this example, Box 4 (yellow) will be placed behind all other boxes because it has a z-index of -1.
Z-Index and Stacking Context:
The z-index property creates a stacking context, which affects how elements are layered. A new stacking context is created in the following scenarios:
- When an element has a
positionvalue other thanstaticand az-indexvalue. - When an element has certain CSS properties set, such as
opacityless than 1