The z-index
property in CSS is used to control the stacking order of elements that overlap with each other. The z-index
property only works on elements that have been positioned with position: absolute
, position: fixed
, or position: relative
.
The z-index
property takes an integer value, with higher values meaning the element will appear on top of elements with lower values. If two elements have the same z-index
value, the element that appears last in the HTML document will be on top.
Here’s an example of how z-index
can be used to control the stacking order of overlapping elements:
.element-1 {
position: relative;
z-index: 2;
}
.element-2 {
position: relative;
z-index: 1;
}
In this example, .element-1
has a higher z-index
value than .element-2
, so it will appear on top of .element-2
. If both elements had the same z-index
value, the element that appears last in the HTML document would be on top.
The z-index
property can also be used in conjunction with other layout properties, such as position
and top
, right
, bottom
, and left
, to create more complex layouts. For example:
.element {
position: absolute;
top: 50px;
left: 100px;
z-index: 2;
}
In this example, the .element
is positioned absolute
, meaning it is positioned relative to the nearest positioned ancestor. The top
property is set to 50px
and the left
property is set to 100px
, so the .element
will be positioned 50 pixels from the top and 100 pixels from the left of its positioned ancestor. The z-index
property is set to 2
, meaning the .element
will appear on top of elements with lower z-index
values.
Overall, the z-index
property is an important tool for controlling the stacking order of elements in CSS layout, and can help you create more dynamic and visually interesting web pages.