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-indexof 1..box2(Green Box) has az-indexof 3..box3(Blue Box) has az-indexof 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-indexvalue (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!
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
