CSS Layout – The z-index Property
The z-index
property specifies the stack order of an element. An element with a greater stack order is always in front of an element with a lower stack order.
1. Understanding z-index
The z-index
property only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky).
Example:
<div class="box box1">Box 1 (z-index: 1)</div>
<div class="box box2">Box 2 (z-index: 2)</div>
<div class="box box3">Box 3 (z-index: 3)</div>
<style>
.box {
position: absolute;
width: 150px;
height: 150px;
margin: 10px;
padding: 20px;
}
.box1 {
top: 50px;
left: 50px;
background-color: #ffccbc;
z-index: 1;
}
.box2 {
top: 100px;
left: 100px;
background-color: #b3e5fc;
z-index: 2;
}
.box3 {
top: 150px;
left: 150px;
background-color: #dcedc8;
z-index: 3;
}
</style>
2. Default Stack Order
If two positioned elements overlap without specifying the z-index
, the element that appears later in the HTML code will be displayed on top.
Example:
<div class="box" style="position: absolute; top: 200px; left: 200px; background-color: #ffe0b2;">Box without z-index</div>
<div class="box" style="position: absolute; top: 250px; left: 250px; background-color: #c8e6c9;">Another box without z-index</div>
<style>
.box {
width: 150px;
height: 150px;
margin: 10px;
padding: 20px;
position: absolute;
}
</style>
3. Using z-index in Complex Layouts
The z-index
property is useful for layering elements in complex layouts, such as dropdown menus, modals, and overlays.
Example:
<div class="box" style="position: relative; z-index: 1; background-color: #b2dfdb;">Relative positioned box with z-index 1</div>
<div class="box" style="position: absolute; top: 300px; left: 300px; z-index: 2; background-color: #ffab91;">Absolute positioned box with z-index 2</div>
<style>
.box {
width: 150px;
height: 150px;
margin: 10px;
padding: 20px;
}
</style>
Conclusion
The z-index
property is a powerful tool in CSS for controlling the stacking order of elements. By understanding and using the z-index
property effectively, you can create complex and visually appealing layouts with overlapping elements.