Stacking contexts
The stacking context is a three-dimensional conceptualization of HTML elements along an imaginary z-axis relative to the user, who is assumed to be facing the viewport or the webpage. HTML elements occupy this space in priority order based on element attributes.
A stacking context is formed, anywhere in the document, by any element in the following scenarios:
- Root element of the document (
<html>). - Element with a
positionvalueabsoluteorrelativeandz-indexvalue other thanauto. - Element with a
positionvaluefixedorsticky(sticky for all mobile browsers, but not older desktop). - Element that is a child of a
flexcontainer, withz-indexvalue other thanauto. - Element that is a child of a
gridcontainer, withz-indexvalue other thanauto. - Element with an
opacityvalue less than1(See the specification for opacity (opens in a new tab)). - Element with a
mix-blend-modevalue other thannormal. - Element with any of the following properties with value other than
none:transformfilterbackdrop-filterperspectiveclip-pathmask/mask-image/mask-border
- Element with an
isolationvalueisolate. - Element with a
will-changevalue specifying any property that would create a stacking context on non-initial value (see this post (opens in a new tab)). - Element with a
containvalue oflayout, orpaint, or a composite value that includes either of them (i.e.contain: strict,contain: content).
Within a stacking context, child elements are stacked according to the same rules previously explained. Importantly, the z-index values of its child stacking contexts only have meaning in this parent. Stacking contexts are treated atomically as a single unit in the parent stacking context.
In summary:
- Stacking contexts can be contained in other stacking contexts, and together create a hierarchy of stacking contexts.
- Each stacking context is completely independent of its siblings: only descendant elements are considered when stacking is processed.
- Each stacking context is self-contained: after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context.