- When the z-index and position attributes are not included, the stacking order of all elements is consistent with the order in which they appear in the HTML document they are in. (Excluding exceptions where negative margins are used to overlap inline elements.)
- When the element floats, the floating block element is placed between the non positioning block element and the positioning block element. In other words, the floating element is displayed above the descendant block element in the regular flow and below the descendant inline element in the regular flow.
- When adding a position attribute to an element, all elements with the position attribute and their child elements will be displayed above other elements that do not have the position attribute.
- The z-index is only valid on elements with the position attribute set, and the z-index attribute is not valid on elements without the position attribute.
The z-index attribute generates a stacked context
A set of elements with a common parent element that move forward or backward together form a stacked context. Each stacked context has a single root element, and when a new stacked context is formed on the element, all child elements in the stacked context are limited to a fixed area in the stacking order. A stacked context forms a whole, and its internal elements have relatively different stacking orders, but when compared to other stacked contexts, they can only be moved up or down as a whole.
The rules for constructing stacked contexts
- The root element of the document
- The element has a position attribute (except for the static attribute) and is also set to the z-index attribute of auto.
- The element has the option attribute and its value is less than 1.
- Some new CSS attributes, such as filters, CSS regions, and other attributes that require off screen rendering, can create stacked contexts for elements.
- Specify the element of position: fixed, with the technical z-index set to auto
The stacking order of sub elements within the same stacking context
From bottom to top (root<- index<index aotu<+index<position):
- The root element of the stacked context.
- The position attribute is set, and elements with negative z-index and their children are placed. Elements with higher z-index values are placed above smaller elements, while elements with the same attribute value are stacked in the order they appear in the HTML.
- There is no element with a position set.
- The position attribute is set and the z-index attribute is an element of auto
- Elements with a position attribute set and a positive z-index attribute.
Different stacking contexts
- Stacking context can be embedded into other stacking contexts.
- Each stacked context and its statistical context are independent.
- Arrange the sub elements in the stacking context in the aforementioned order.
- The z-index of child stacking contexts within the stacking context only has meaning within the parent stacking context.