📜  css z index - CSS (1)

📅  最后修改于: 2023-12-03 14:40:17.805000             🧑  作者: Mango

CSS z-index

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).

Syntax
element {
  z-index: value;
}
  • element: The HTML element to which the z-index property is applied.
  • value: A positive or negative integer representing the desired z-index. Elements with higher z-index values will appear in front of elements with lower values.
Usage

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).

Tips
  1. 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.

  2. 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.

  3. When two elements have the same z-index value, they will appear in the order they appear in the HTML code.

  4. 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.

Conclusion

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.