The z-index
property in CSS controls the stacking order of elements on a webpage.
Stacking order determines which elements appear in front of or behind others.
This is especially useful when elements overlap.
How z-index
Works:
- Positive Values: Higher values bring the element closer to the front.
- Negative Values: Lower values push the element further back.
- Auto (Default): The element follows the natural HTML order, meaning it stacks according to the order it appears in the document.
Important Notes:
- Positioned Elements: The
z-index
only works on elements that have a positioning value other thanstatic
(the default). - This means you must set
position: relative
,position: absolute
,position: fixed
, orposition: sticky
for thez-index
to take effect.
Simple Stacking Order
<style> .box { width: 100px; height: 100px; position: absolute; } .box1 { background-color: red; top: 50px; left: 50px; z-index: 1; } .box2 { background-color: blue; top: 70px; left: 70px; z-index: 2; } </style> <div class="box box1"></div> <div class="box box2"></div>
- Box 1 (
.box1
) is red and has az-index
of 1. - Box 2 (
.box2
) is blue and has az-index
of 2.
Since Box 2
has a higher z-index
, it will appear on top of Box 1
, even though it is added after Box 1
in the HTML.
Using Negative z-index
<style> .box { width: 100px; height: 100px; position: absolute; } .box1 { background-color: green; top: 50px; left: 50px; z-index: 1; } .box2 { background-color: yellow; top: 70px; left: 70px; z-index: -1; } </style> <div class="box box1"></div> <div class="box box2"></div>
- Box 1 (
.box1
) is green and has az-index
of 1. - Box 2 (
.box2
) is yellow and has az-index
of -1.
Since Box 2
has a negative z-index
, it will appear behind Box 1
, even though it is placed on top of Box 1
in the HTML.
Conclusion:
The z-index
property is an essential tool in managing the visual stacking of elements on a webpage.
It helps create layered designs, ensuring that elements are displayed in the correct order, whether in front or behind each other.