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
position
valueabsolute
orrelative
andz-index
value other thanauto
. - Element with a
position
valuefixed
orsticky
(sticky for all mobile browsers, but not older desktop). - Element that is a child of a
flex
container, withz-index
value other thanauto
. - Element that is a child of a
grid
container, withz-index
value other thanauto
. - Element with an
opacity
value less than1
(See the specification for opacity (opens in a new tab)). - Element with a
mix-blend-mode
value other thannormal
. - Element with any of the following properties with value other than
none
:transform
filter
backdrop-filter
perspective
clip-path
mask
/mask-image
/mask-border
- Element with an
isolation
valueisolate
. - Element with a
will-change
value specifying any property that would create a stacking context on non-initial value (see this post (opens in a new tab)). - Element with a
contain
value 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.