Explain CSS z-index Property
The z-index
property in CSS controls the stacking order of elements on a web page. Elements with a higher z-index
value are displayed in front of elements with a lower z-index
value. This property only works on elements that have a position value other than static
(i.e., relative
, absolute
, fixed
, or sticky
).
Here’s a basic example to illustrate how z-index
works:
HTML:
<div class="container">
<div class="box box1">Box 1</div>
<div class="box box2">Box 2</div>
<div class="box box3">Box 3</div>
</div>
CSS:
.container {
position: relative;
width: 300px;
height: 200px;
}
.box {
position: absolute;
width: 100px;
height: 100px;
color: white;
display: flex;
align-items: center;
justify-content: center;
}
.box1 {
background-color: red;
z-index: 1;
top: 20px;
left: 20px;
}
.box2 {
background-color: green;
z-index: 3;
top: 40px;
left: 40px;
}
.box3 {
background-color: blue;
z-index: 2;
top: 60px;
left: 60px;
}
Explanation:
.box1
(Red Box) has az-index
of 1..box2
(Green Box) has az-index
of 3..box3
(Blue Box) has az-index
of 2.
In this example:
- The Green Box (
.box2
) will be on top of both the Red Box (.box1
) and the Blue Box (.box3
), because it has the highestz-index
value (3). - The Blue Box (
.box3
) will be in the middle, because itsz-index
(2) is higher than the Red Box'sz-index
(1) but lower than the Green Box's. - The Red Box (
.box1
) will be at the bottom, as it has the lowestz-index
.
You can also use z-index
with negative values. Elements with negative z-index
values will be placed behind elements with z-index
values of zero or higher.
Example with Negative z-index
:
.box4 {
background-color: yellow;
z-index: -1;
top: 10px;
left: 10px;
}
In this case, the Yellow Box (.box4
) will be behind all other elements with z-index
values of 0 or higher.
Let me know if you need more examples or explanations!
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.