CSS Z-index is a property that allows you to control the vertical stacking order of elements on a web page. It determines which element appears on top of another element when they overlap. The higher the z-index value, the closer the element is to the viewer and the more likely it is to be displayed on top of other elements.
The z-index property only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky). If an element is not positioned, the z-index property will have no effect.
Here is an example of how to use the z-index property:
.box1 {
position: relative;
z-index: 1;
}
.box2 {
position: relative;
z-index: 2;
}
In this example, box2 will appear on top of box1 because it has a higher z-index value.
You can also use negative values for the z-index property. Elements with negative z-index values will appear behind elements with positive z-index values. Here is an example:
.box1 {
position: relative;
z-index: 1;
}
.box2 {
position: relative;
z-index: -1;
}
In this example, box2 will appear behind box1 because it has a negative z-index value.
It is important to note that the z-index property only affects elements that are siblings (i.e., have the same parent element). If you want to control the stacking order of elements that are not siblings, you will need to use a different approach, such as changing the order of the elements in the HTML or using absolute positioning.
Here is an example of how to use absolute positioning to control the stacking order of elements:
.box1 {
position: absolute;
top: 0;
left: 0;
}
.box2 {
position: absolute;
top: 50px;
left: 50px;
}
In this example, box2 will appear on top of box1 because it comes after box1 in the HTML and has a higher z-index value.
Overall, the z-index property is a powerful tool for controlling the visual hierarchy of elements on a web page. By using z-index, you can ensure that important elements are always visible and that the layout of your page is clear and easy to understand.