The z-index
property in CSS controls the stacking order of elements that overlap. Elements with a higher z-index
value will appear in front of those with a lower z-index
value. The z-index
property only works on positioned elements (position: relative
, position: absolute
, position: fixed
, or position: sticky
).
Key points
Default Value: The default value for z-index
is auto
, which means the element will follow the order of the HTML structure.
Higher Values in Front: Elements with higher z-index
values are stacked in front of elements with lower values.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
color: white;
font-size: 20px;
text-align: center;
line-height: 100px;
}
.box1 {
background-color: red;
top: 50px;
left: 50px;
z-index: 1;
}
.box2 {
background-color: blue;
top: 80px;
left: 80px;
z-index: 3;
}
.box3 {
background-color: green;
top: 110px;
left: 110px;
z-index: 2;
}
</style>
</head>
<body>
<div class="box box1">1</div>
<div class="box box2">2</div>
<div class="box box3">3</div>
</body>
</html>
Notes:
1. Negative Values: z-index
can have negative values, which place elements behind those with a z-index
of 0 or higher.
2. Non-Positioned Elements: If an element is not positioned (i.e., position: static
), the z-index
property does not apply to it.