📅  最后修改于: 2023-12-03 14:40:17.805000             🧑  作者: Mango
The z-index
property in CSS allows you to control the visibility and overlapping of elements in a web page. In simple terms, it specifies the stacking order of elements on the z-axis (the axis going from the screen towards the viewer).
element {
z-index: value;
}
z-index
property is applied.When two or more elements overlap, the z-index
property determines which one appears on top. By default, elements have a z-index
of 0 and appear in the order they appear in the HTML code. However, you can change the stacking order by setting the z-index
property for each element.
For example, consider a page with a header, main content, and footer section. You can set the z-index
property for each section to ensure that they appear in the desired order with respect to one another.
<header style="position: fixed; z-index: 1;">...</header>
<main style="position: relative; z-index: 0;">...</main>
<footer style="position: fixed; z-index: 1;">...</footer>
In the above example, the header
and footer
sections are set to position: fixed
, which means they are positioned relative to the viewport and will not move when the user scrolls the page. The main
section is set to position: relative
, which means it is positioned relative to its parent element and will move as the user scrolls.
The header
and footer
sections are also given a z-index
of 1, which ensures that they appear on top of the main
section (which has a z-index
of 0).
You can use negative z-index
values to position an element behind other elements. However, be careful not to use extremely large or small values, as this can cause display issues.
z-index
only works on positioned elements (position: absolute
, position: fixed
, position: relative
, or position: sticky
). If an element is not positioned, the z-index
property has no effect.
When two elements have the same z-index
value, they will appear in the order they appear in the HTML code.
If you want to change the stacking order of child elements within a parent element, you can set the parent element's z-index
to a non-zero value and the child elements' z-index
to a value relative to the parent.
The z-index
property is a powerful tool for controlling the stacking order of elements in a web page. By setting the z-index
property for each element, you can ensure that elements appear in the desired order with respect to one another. However, be careful not to use extremely large or small values, and make sure to only use z-index
on positioned elements.