CSS Z-index
CSS Z-index
The z-index property controls the vertical stacking order of positioned elements. It determines which elements appear in front of or behind others when they overlap.
z-index only works on elements with a position value other than static.
Basic Z-index
Elements with a higher z-index value appear on top of elements with a lower value.
.box-a {
position: relative;
z-index: 1;
}
.box-b {
position: relative;
z-index: 2;
}
In this example, .box-b will appear above .box-a.
Overlapping Elements
When elements overlap, z-index controls which one is visible on top.
.card {
position: absolute;
width: 200px;
height: 120px;
}
.card.one {
top: 20px;
left: 20px;
z-index: 1;
}
.card.two {
top: 40px;
left: 40px;
z-index: 3;
}
Negative Z-index
You can use negative values to place elements behind others.
.background {
position: absolute;
z-index: -1;
}
Be careful with negative values, as elements may become unclickable or hidden.
Stacking Context
A stacking context is a group of elements that share a common stacking order. Once a stacking context is created, child elements are stacked only within that context.
A new stacking context is created when:
- An element has
positionand az-indexvalue - An element uses
opacityless than 1 - An element uses
transform,filter, orperspective
.parent {
position: relative;
z-index: 1;
}
.child {
position: absolute;
z-index: 999;
}
Even with a high value, .child cannot escape the stacking context of .parent.
Z-index and Source Order
If two elements have the same z-index, the one that appears later in the HTML will be on top.
.box {
position: relative;
z-index: 1;
}
Code Challenge
Goal: Control which elements appear on top using z-index.
HTML:
<div class="scene"> <div class="layer back">Back</div> <div class="layer middle">Middle</div> <div class="layer front">Front</div> </div>
Task:
- Position the layers so they overlap
- Place
.fronton top - Place
.backbehind the others
Try a Solution:
.scene {
position: relative;
height: 200px;
}
.layer {
position: absolute;
width: 160px;
height: 100px;
padding: 10px;
border: 1px solid #ddd;
}
.back {
top: 20px;
left: 20px;
z-index: 1;
}
.middle {
top: 40px;
left: 40px;
z-index: 2;
}
.front {
top: 60px;
left: 60px;
z-index: 3;
}
What’s Next?
Next, you will learn how to handle overflowing content using CSS overflow.