What Is Meant by "Stacking Context" in CSS?

In CSS, "stacking context" is merely how a parent element and its descendants are treated as a group, such that the following things are done in isolation from elements outside the stacking context:

  1. Descendants are composited and blended with other elements within the same context;
  2. z-index, opacity, transforms, and clipping/masking are calculated relative to the context they're in.

The default stacking context is the root element of the document (<html>). However, other HTML elements on the page can create their own stacking context when the following CSS properties are specified on them:

  1. Compositing and Blending Properties:
    • opacity value set to less than 1;
    • mix-blend-mode set to value other than normal;
    • transform, filter, backdrop-filter, perspective, clip-path, mask, mask-image or mask-border set to value other than none;
    • isolation value set to isolate.
  2. Positioning Properties:
    • position value set to absolute or relative, having z-index value other than auto;
    • position value set to fixed or sticky.
  3. Layout Properties:
    • Child of a flex or grid container with z-index value other than auto.
  4. Performance Properties:
    • will-change value specifying any property that might change, directing the browser to create a new composite layer for that element;
    • contain value set to layout or paint, or a composite value that includes either of them (i.e. contain: strict, contain: content).

For example:

<div id="parent-1">
  <code>z-index: 1</code>
  <div id="child-1"><code>z-index: 3</code></div>
</div>

<div id="parent-2">
  <code>z-index: 2</code>
  <div id="child-2"><code>z-index: auto</code></div>
</div>
#parent-1 {
  width: 300px;
  height: 300px;
  position: absolute;
  z-index: 1;
  background: aqua;
}

#child-1 {
  position: relative;
  z-index: 3;
  background: yellow;
}

#parent-2 {
  width: 200px;
  height: 200px;
  position: relative;
  z-index: 2;
  background: pink;
}

In this example, "child-1" is rendered behind "parent-2" even though it has a higher z-index value. This is because the z-index of all descendants of a parent that establishes a new stacking context, is relative to the parent's stacking order, which in this case, is positioned behind "parent-2". This means that elements with a higher z-index value are only positioned on top of elements with a lower z-index value within the same stacking context.

It's important to note that creating too many stacking contexts can negatively impact web page performance. Therefore, it's important to use them only when necessary.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.