Free beginner tutorial

CSS z-index and Stacking Contexts

The CSS z-index property helps control which overlapping elements appear in front. To understand why a large value sometimes has no effect, learn how stacking contexts group elements into independent layers.

Quick answer: compare z-index values only among elements in the same stacking context. A child cannot escape its parent stacking context just by using a very large number.

Set a stacking order with z-index

When elements overlap, a higher stack level is generally drawn above a lower one in the same stacking context. z-index applies to positioned elements and also to flex or grid items. For positioned elements, auto is the default; an integer sets the stack level and creates a local stacking context.

.card {
  position: relative;
  z-index: 1;
}

.card-menu {
  position: absolute;
  inset-block-start: 100%;
  z-index: 2;
}

What is a stacking context?

A stacking context is a group of elements whose layers are ordered together. The browser first determines the order inside that group, then treats the group as one layer in its parent context. Child z-index values are not directly compared with elements outside their own context.

Why does a large z-index value not work?

Check the ancestors of the element. If a parent creates a stacking context that is behind another sibling context, increasing a child's z-index cannot lift it above that outside sibling. Raise or reorganize the parent context, or place the overlapping element at a suitable level in the document structure.

.panel {
  position: relative;
  z-index: 1;
}

.dialog-layer {
  position: relative;
  z-index: 2;
}

Common stacking-context creators include the root element, positioned elements with a non-auto z-index, fixed or sticky elements, transforms, and opacity values below 1. The full list includes additional properties, so check the relevant CSS reference when debugging a complex layout.

Use a small, deliberate layer scale

Choose a short scale for interface layers—such as content, menus and dialogs—and document it with CSS custom properties. Avoid assigning arbitrary huge numbers everywhere; the parent stacking context still determines how a nested group compares with its neighbors.

:root {
  --layer-content: 0;
  --layer-menu: 10;
  --layer-dialog: 20;
}

.site-menu { z-index: var(--layer-menu); }
.dialog { z-index: var(--layer-dialog); }

Continue learning

See CSS positioning to learn about relative, absolute, fixed and sticky elements. Use Flexbox and CSS Grid for page layout.

For the detailed stacking rules, read MDN's z-index guide and the W3Schools CSS z-index tutorial.