2 min read

Z-Index and Stacking Context

The z-index property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order. However, z-index only works on positioned elements (position: absolute, relative, fixed, or sticky) and flex items.

1. The z-index Property

  • Values: Integer (positive, negative, or zero). auto is the default.
  • Behavior: Higher numbers are closer to the user (on top). Lower numbers are further away (behind).
img {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: -1; /* Behind other content */
}

2. Stacking Context

A common confusion is when an element with z-index: 999 is still behind an element with z-index: 1. This happens because of Stacking Contexts.

A stacking context is a three-dimensional conceptualization of HTML elements along an imaginary z-axis relative to the user.

How a Stacking Context is Formed

A new stacking context is formed by any element that meets specific criteria, including:

  • It is the root element (<html>).
  • It has a position value other than static and a z-index value other than auto.
  • It has a position value of fixed or sticky.
  • It is a child of a flex container, with z-index value other than auto.
  • It is a child of a grid container, with z-index value other than auto.
  • It has an opacity value less than 1.
  • It has a transform, filter, perspective, clip-path, mask / mask-image / mask-border value other than none.
  • It has isolation: isolate.

The Rules of Stacking

  1. Within a Stacking Context: Elements are stacked according to their z-index.
  2. Between Stacking Contexts: Stacking contexts are atomic. If Element A creates a stacking context, all of its children are confined within that context.
    • If Context A is below Context B, no child of A can ever be above any child of B, regardless of how high their z-index is.

Example

<div id="div1" style="position: relative; z-index: 1;">
  <div id="child1" style="position: absolute; z-index: 999;">I am Child 1</div>
</div>

<div id="div2" style="position: relative; z-index: 2;">
  <div id="child2" style="position: absolute; z-index: 1;">I am Child 2</div>
</div>

Result: child2 will be on top of child1.

  • div1 has z-index: 1.
  • div2 has z-index: 2.
  • Therefore, div2 (and all its contents) is on top of div1.
  • child1's z-index: 999 is only relevant inside div1. It cannot break out to beat div2.

3. isolation: isolate

The isolation property defines whether an element must create a new stacking context.

  • auto: Default.
  • isolate: Forces the element to create a new stacking context.

This is useful when you want to ensure an element's children don't interact with the z-ordering of elements outside their parent, without needing to set position or z-index.

.container {
  isolation: isolate;
}

programming/css/css programming/css/positioning programming/css/flexbox programming/css/grid-layout