The z-index property in CSS is used to control the stacking order of positioned elements. Elements with a higher z-index value are displayed in front of elements with lower z-index values. Here are a few examples demonstrating the use of the z-index property:
Example 1:
Stacking Div Elements
<!DOCTYPE html><html lang=”en”><head><meta charset=”UTF-8″><meta name=”viewport” content=”width=device-width, initial-scale=1.0″><style>.box {position: relative;width: 100px;height: 100px;margin: 20px;background-color: #f0f0f0;border: 1px solid #ccc;}.box1 {z-index: 1;}.box2 {z-index: 2;background-color: #aeeeee;left: 50px;top: 20px;}.box3 {z-index: 3;background-color: #98fb98;left: 100px;top: 40px;}</style><title>z-index Example 1</title></head><body><div class=”box box1″>Box 1</div><div class=”box box2″>Box 2</div><div class=”box box3″>Box 3</div></body></html>
In this example:
- .box1 has the default z-index of 0.
- .box2 has a higher z-index than .box1.
- .box3 has an even higher z-index than .box2.
Output:
Example 2:
Stacking Positioned Elements
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<style>
.container {
position: relative;
}.box {
position: absolute;
width: 100px;
height: 100px;
margin: 20px;
background-color: #f0f0f0;
border: 1px solid #ccc;
}.box1 {
z-index: 1;
}.box2 {
z-index: 2;
background-color: #aeeeee;
left: 50px;
top: 20px;
}.box3 {
z-index: 3;
background-color: #98fb98;
left: 100px;
top: 40px;
}
</style>
<title>z-index Example 2</title>
</head>
<body>
<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>
</body>
</html>
In this example:
- All
.box
elements are positioned absolutely within a relative container - The stacking order is controlled using the
z-index
property.
Output: