Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 139 ยท Layout Fundamentals

z-index and Stacking Contexts

Learn how browsers decide which element is on top, how z-index really works, what creates a stacking context, and how to debug a z-index that seems ignored.

A web page looks flat, but the browser paints it in layers. When two boxes overlap, something has to decide which one is drawn on top. Usually you never notice, because in normal flow boxes do not overlap. But as soon as you use positioning, negative margins or transforms, overlap is everywhere: dropdowns over content, modals over the page, sticky headers over scrolling text.

z-index is the property that controls this order along the "z axis," the imaginary line pointing out of the screen toward you. It looks simple: bigger number, closer to the front. Yet it is famous for not working, with developers escalating to z-index: 99999 and still losing. The reason is stacking contexts, and once you understand them, z-index problems take minutes to solve instead of hours.

The default painting order

Without any z-index, the browser paints the contents of a page in a fixed order, from back to front. Simplified:

  1. The backgrounds and borders of the root element.
  2. Non-positioned block boxes, in source order.
  3. Floated boxes.
  4. Non-positioned inline content, such as text and images.
  5. Positioned elements (anything except position: static), in source order.

Two rules of thumb follow. Positioned elements are painted above non-positioned ones. And among elements of the same kind, later in the HTML means on top.

How z-index works

z-index takes an integer, positive, zero or negative, and moves an element forward or backward within that order:

  • Higher numbers are painted on top of lower numbers.
  • Elements with the same value fall back to source order.
  • z-index: auto (the default) means "no special layer"; the element is painted with the positioned elements at level 0.
  • Negative values put an element behind its non-positioned siblings, and even behind the background of its parent, as long as that parent does not form a stacking context.

z-index only has an effect on positioned elements, and on flex and grid items. On a plain static block it is ignored.

z-index on overlapping cards

With no z-index, C is on top because it comes last. Add z-index: 3 to .a and A jumps to the front. Give .c a z-index: -1; it slips behind the others, but stays above the page background, because .stage does not create a stacking context. You will see why that matters in a moment.

Stacking contexts: layers inside layers

Here is the key idea. A stacking context is a group of elements that are stacked together as one unit. Inside the group, children are ordered by their own z-index values. But from the outside, the whole group is placed at a single level: the level of the element that created it.

Think of it like folders in a pile of paper. You can reorder the sheets inside a folder however you like, but no sheet can escape its folder. If the folder is under another folder, every sheet in it is under that other folder, even a sheet marked "99999."

The page's root element (<html>) creates the first stacking context. Many properties create a new one on an element:

  • position: relative or absolute with a z-index other than auto;
  • position: fixed or sticky (always, even without a z-index);
  • a flex or grid item with a z-index other than auto;
  • opacity less than 1;
  • transform, scale, rotate, translate, filter, backdrop-filter, perspective, clip-path or mask with any value other than none;
  • mix-blend-mode other than normal, or isolation: isolate;
  • will-change naming one of the properties above;
  • contain: layout or contain: paint, and container-type: size or inline-size.

You do not need to memorize the list. Remember that it includes the common visual effects (opacity, transforms, filters) and that when z-index acts strangely, one of these is almost always involved.

Debugging a z-index war

Here is the most typical bug. A page has a header with a dropdown menu and a "hero" section below it. The dropdown has z-index: 9999, but it still disappears behind the hero:

Why z-index: 9999 loses

Walk through it the way you would in DevTools:

  1. Find the elements involved. The menu (which should be on top) and the hero (which wins).
  2. Walk up from each one to find its stacking context. The menu's nearest ancestor that creates one is header, thanks to position: relative plus z-index: 1. The hero creates its own.
  3. Find the level where they become siblings. Both header and .hero sit in the root stacking context. That is where the decision is made: header at 1, hero at 2. The hero wins.
  4. The menu's 9999 never enters that comparison. It only orders the menu among the header's own children.

There are several fixes. Try each in the example:

  • Give header a higher z-index than the hero, for example z-index: 3. The header and everything in it now sit above the hero.
  • Remove the z-index from .hero. It is positioned, but with z-index: auto it creates no stacking context of its own, and the header at level 1 wins.
  • Remove the z-index from header. Then the header no longer forms a stacking context, the menu's 9999 is compared at the root level, and it wins.

The first fix is usually the right one: it states the intent ("the site header sits above page content") at the level where the decision is made.

DevTools can help. Chrome and Edge have a Layers panel that shows composited layers in 3D, and the Computed panel shows each element's z-index and position. Firefox's Inspector marks elements that create a stacking context. When you are stuck, check the ancestors of both elements for any property from the list above.

A stacking context created by accident

Sometimes no z-index was involved at all. Here, a tooltip inside a card should overlap the next card, but a harmless-looking opacity: 0.99 (or a transform used for a hover effect) traps it:

opacity and transform create stacking contexts too

opacity: 0.99 makes the first card a stacking context at level 0. The second card is also at level 0, comes later in the source, and therefore wins. Delete the .faded rule and the tooltip's z-index: 10 competes at the root level, so it appears above the second card.

Keeping z-index under control

Most z-index chaos comes from random numbers picked in the heat of the moment. A few habits prevent it:

  • Use a small, named scale. Store layers as custom properties in one place:

    CSS
    :root {
      --z-dropdown: 10;
      --z-sticky: 20;
      --z-overlay: 30;
      --z-modal: 40;
      --z-toast: 50;
    }
    .site-header { position: sticky; top: 0; z-index: var(--z-sticky); }
    
  • Contain components with isolation: isolate. A card that uses z-index: 1 and z-index: 2 internally should get isolation: isolate on its root. Its inner numbers then cannot leak out and fight with the rest of the page. You saw this property in Blend Modes.

  • Leave z-index off when source order already works. Later elements are on top by default.

  • Use the top layer for dialogs. A modal <dialog> opened with showModal(), and a popover, are drawn in the browser's top layer, above every z-index on the page. No number can beat it, which is exactly what you want for modals. See the HTML lesson on dialogs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two positioned siblings both have z-index: auto. Which one is on top?

    With equal stacking levels, the browser falls back to source order, so the later element is painted on top.
  2. 2. A dropdown with z-index: 9999 is hidden behind a section with z-index: 2. The dropdown's parent header has position: relative; z-index: 1. Why?

    The header forms a stacking context, so everything inside it is placed at the header's level when compared with the section.
  3. 3. Which of these does NOT create a stacking context?

    A relatively or absolutely positioned element only creates a stacking context when it also has a z-index other than auto.
  4. 4. What is the cleanest way to keep a component's internal z-index values from interfering with the rest of the page?

    isolation: isolate creates a stacking context with no visual side effects, so internal layers stay internal.

Summary

  • Without z-index, positioned elements paint above non-positioned ones, and later elements paint above earlier ones.
  • z-index works on positioned elements and flex or grid items; higher numbers come forward.
  • A stacking context groups an element with its descendants; nothing inside can rise above something outside that beats the group.
  • Stacking contexts come from z-index on positioned elements, fixed and sticky positioning, opacity, transforms, filters, isolation and more.
  • To debug, walk up from both elements to the level where their stacking contexts are siblings, and fix the order there.
  • Use a named z-index scale, isolation: isolate for components, and the top layer for dialogs.

Next: Floats โ€” wrap text around images, and learn why floats are no longer used for page layout.