In CSS, the z-index
property is used to control the stacking order of positioned elements. Elements with a higher z-index
value will be positioned in front of elements with a lower z-index
value. This property is particularly useful when you have overlapping elements on a webpage and you want to control the order in which they appear.
Here's a basic overview of how to use the z-index
property:
cssselector { z-index: value; }
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.element1 {
position: absolute;
top: 50px;
left: 50px;
background-color: red;
width: 100px;
height: 100px;
z-index: 2;
}
.element2 {
position: absolute;
top: 70px;
left: 70px;
background-color: blue;
width: 100px;
height: 100px;
z-index: 1;
}
</style>
</head>
<body>
<div class="element1"></div>
<div class="element2"></div>
</body>
</html>
In this example, we have two absolutely positioned elements (element1
and element2
). The z-index
property is used to control their stacking order. The red box (element1
) has a higher z-index
than the blue box (element2
), so it will appear in front of the blue box.
Keep in mind a few key points:
z-index
only works on positioned elements (elements with a position
value other than static
).
z-index
values can be both positive and negative integers, and even decimal numbers.
The stacking context is crucial when working with z-index
. An element with a higher z-index
might not appear in front if it is not within the same stacking context as the other elements. Understanding stacking contexts is important for more complex layouts.
Feel free to modify the values and experiment to see how z-index
affects the stacking order of elements.