📜  css z-index - CSS (1)

📅  最后修改于: 2023-12-03 15:00:05.995000             🧑  作者: Mango

CSS z-index

The CSS z-index property specifies the stack order of an element. This property controls the vertical stacking order of positioned elements that have a z-index value other than auto. Elements with higher z-index values are stacked in front of elements with lower z-index values.

Syntax

The syntax for the z-index property is as follows:

z-index: auto|number|initial|inherit;
  • auto: The default value. The element does not have a specified stack order and will be placed in the normal stack order of the web page.
  • number: Specifies the stack order of the element. A higher value will place the element in front of elements with lower values. Negative values are allowed.
  • initial: Sets the property to its default value.
  • inherit: Inherits the property from its parent element.
Example
.parent {
  position: relative;
  z-index: 1;
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}

In this example, the parent element has a z-index value of 1, while the child element has a z-index value of 2. This means that the child element will overlap the parent element, as it has a higher z-index value.

Notes
  • The z-index property only applies to positioned elements (position: absolute, position: relative, position: fixed, or position: sticky).
  • If two positioned elements overlap without a z-index value, the element that appears later in the HTML source will be placed on top.
  • If two elements have the same z-index value, the element that appears later in the HTML source will be placed on top.
  • z-index values are not limited to integers and can contain decimal values. However, comparing two z-index values with different units (e.g. 2 and 2px) is not possible, as the units are not compatible.
  • The z-index property can also be used in conjunction with the opacity property to create translucent layers. By setting a lower z-index value on a semi-transparent element, it will appear to be behind other elements on the page.