Thuta Learning
CSS
IntermediateWeb DevelopmentBeginner

Z-Index

CSSLesson 1630 min

What you'll walk away with

  • Check that an element is positioned, or a flex/grid item, before expecting z-index to work
  • Recognise the properties that create a stacking context: positioned with z-index, opacity, transform, isolation and more
  • Explain why a child's z-index can never climb out of its parent's context
  • Build a layer-token scale with custom properties and use isolation: isolate

Explain it simply

Explain it simply

When elements overlap, the browser paints them from bottom to top, like sheets of paper stacked on a desk. z-index gives a sheet a number that says "put me higher": the bigger the number, the higher it sits. Modals, dropdowns, tooltips and sticky headers all depend on it.

Some sheets, though, live inside a folder. Give a sheet inside a folder 9999 and it still stays under any folder that sits above its own folder, because it moves together with the folder. That folder is called a stacking context.

Problem → Why → Solution

The problem: the dropdown slides under the content

You open the dropdown menu in the header and it slides underneath the hero section below. You give the dropdown z-index: 9999, then 999999, and nothing changes. The hero only has z-index: 2, and 9999 is clearly bigger than 2.

layers.css
.header   { position: relative; z-index: 1; }
.dropdown { position: absolute; top: 100%; z-index: 9999; }
.hero     { position: relative; z-index: 2; }

/* <header class="header"><nav class="dropdown">...</nav></header>
   <section class="hero">...</section> */

Why does 9999 lose?

.header has position: relative and z-index: 1, so it forms a stacking context. The dropdown's 9999 is compared only inside the header, and at root level the whole header counts as a single layer with value 1. At the root, 1 is compared with 2 and the hero wins. The fix is not a bigger number on the dropdown; it is raising the header above the hero, or removing the hero's z-index.

Core concept: stacking contexts are folders

Without any z-index, the browser paints in a fixed order: the context's background first, then normal-flow blocks, floats, inline content, and finally positioned elements in HTML order. That is why, of two overlapping positioned siblings, the one written later in the HTML appears on top. Reordering the HTML is therefore a legitimate fix in its own right, and it often removes the need for any z-index at all.

z-index changes that order, but it only works on elements whose position is not static (relative, absolute, fixed, sticky) and on flex and grid items. Giving a static block z-index: 5 does nothing. Negative values are allowed: they send an element behind the normal content of its context, though never below that context's own background.

A stacking context is a folder with its own z-index numbering. The children inside are compared with each other, and then the whole folder is placed into its parent context as one layer. A child is never compared directly with elements outside its folder.

The most common properties that create a new context are listed below. opacity and transform are the riskiest, because they slip in quietly through animations.

PropertyCreates a context when
position: relative / absolutez-index is not auto
position: fixed / stickyAlways
opacityLess than 1, even 0.99
transform / filterNot none
isolationSet to isolate

Contexts can nest: a folder can sit inside another folder. To compare two elements, walk up each one's ancestors and find the first context they share. Inside that shared context, the competitors are often not the two elements themselves but the two ancestors that represent them.

Working out who is on top
  1. Check both are positioned
  2. Walk up to each one's context
  3. Find the shared parent context
  4. Compare z-index at that level only

Before raising any number, inspect both elements' ancestors in DevTools to see which folders they live in.

General pattern

css
:root {
  --z-layer-name: number;  /* one token per layer */
}

element {
  position: relative | absolute | fixed | sticky;
  z-index: var(--z-layer-name);
}

component {
  isolation: isolate;  /* new context, no z-index needed */
}

Name each layer with a custom-property token and use it through var(). When a component's internal z-index values must not leak out, give the component isolation: isolate.

Example: a modal and its backdrop

When a modal opens, the backdrop that dims the page and the modal box are two separate layers. Both are fixed and are direct children of body, so they are compared side by side in the root context.

.modal-backdrop {
  position: fixed;
  inset: 0;
  z-index: 100;
}

.modal {
  position: fixed;
  z-index: 101;
}

Code breakdown

  1. Line 2position: fixed;

    Pins the backdrop to the viewport, and being fixed also makes it a stacking context.

  2. Line 3inset: 0;

    Sets all four offsets to 0, so the backdrop covers the whole viewport and blocks clicks on the page underneath.

  3. Line 4z-index: 100;

    A high layer value puts it above page content; other positioned elements on the page must stay below 100.

  4. Line 9z-index: 101;

    Modal and backdrop share the root context, so the plain comparison 101 > 100 really decides it. A real modal also needs top/left (or inset) to place it; this snippet only shows the layering.

You should see
The backdrop covers the whole page, and the modal box appears above the backdrop.

Tracking down a stacking bug in DevTools

1. Select the element that is covered

Select the dropdown in the Elements panel and check position and z-index in the Computed tab. If position is static, that is already the whole bug.

2. Walk up the ancestors

Select each parent in turn and look for a positioned z-index, opacity, transform, filter or isolation. The first ancestor you find is the dropdown's folder.

3. Fix it at the folder level

Raise that folder above the covering element's folder, or remove the context nobody needed. Chromium's Layers panel can also show the composited layers in 3D.

In real projects

Where this shows up in real projects

On big projects, developers adding ever larger values such as 999, 9999 and 99999 is known as the z-index arms race. Teams prevent it with a single token scale, for example --z-dropdown: 100; --z-sticky: 200; --z-modal: 300; --z-toast: 400;, and the rest of the code only uses the tokens. A new layer means a reviewed change to that one scale, and anyone reading .menu { z-index: var(--z-dropdown); } instantly knows its intended place in the stack.

Modal and tooltip libraries for frameworks such as React and Vue usually render their content through a portal at the end of body. That keeps the overlay out of any parent context created by a transform or a z-index. Components with decorative layers give their root element isolation: isolate so internal negative z-index values stay inside the component.

Common mistakes

Common mistakes

1. Putting z-index on a static element

Writing .tooltip { z-index: 10; } without a position (and not as a flex or grid item) is ignored entirely. DevTools often greys out the declaration with a hint; add position: relative.

2. Raising the child instead of its context

If a dropdown at 9999 loses, adding digits will never help. Find the ancestor that created the context and fix that element's z-index, or remove the context it does not need.

3. Missing a context created by an animation

A fade-in's opacity: 0.99 or a slide-in's transform creates a new context for as long as it applies, sometimes permanently. If a tooltip gets covered only while an animation runs, suspect this first.

Best practices

Best practices

  • Space the token values 100 apart so a new layer can be slotted in between later.
  • Keep z-index values inside a component tiny, such as 1, 2 and 3, and give the component root isolation: isolate.
  • Render app-wide overlays such as modals and toasts at the end of body.

Mini challenge

Mini challenge: rescue the dropdown with a layer scale

In the starter, the dropdown hides under the hero. Build a layer-token scale to fix it, and keep the hero's decoration visible.

  • Define three increasing tokens on :root: --z-header, --z-modal and --z-toast
  • The dropdown shows above the hero without giving it 9999
  • The hero's ::before decoration (z-index: -1) stays visible above the hero's background
  • The toast sits above the modal
layers.html
<style>
  :root {
    /* TODO: --z-header, --z-modal, --z-toast */
  }
  .header { position: relative; z-index: 1; }       /* TODO: use a token */
  .dropdown { position: absolute; top: 100%; z-index: 9999; }
  .hero { position: relative; z-index: 2; }  /* TODO: no z-index, still a context */
  .hero::before { content: ""; position: absolute; z-index: -1; }
  .modal { position: fixed; }                       /* TODO: token */
  .toast { position: fixed; }                       /* TODO: token, above modal */
</style>

<header class="header">Shop <nav class="dropdown">Menu</nav></header>
<section class="hero">Big sale</section>
<div class="modal">Sign in</div>
<div class="toast">Saved!</div>

Expected: The header's yellow dropdown appears over the hero. Inside the hero, the dark blue decoration box shows above the hero's background and behind the "Big sale" text. Where the toast overlaps the modal, the toast is on top.

Show hint

Removing the hero's z-index removes its context, and ::before would then fall behind the hero's background. Use the property that creates a context without any z-index.

Show solution
layers.html
<style>
  :root {
    --z-header: 100;
    --z-modal: 300;
    --z-toast: 400;
  }
  body { margin: 0; }
  .header { position: relative; z-index: var(--z-header); height: 50px; }
  .dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    width: 200px;
    height: 120px;
    background: #fde68a;
  }
  .hero { position: relative; isolation: isolate; height: 200px; background: #e0f2fe; }
  .hero::before {
    content: "";
    position: absolute;
    inset: 20px;
    z-index: -1;
    background: #1e3a8a;
  }
  .modal { position: fixed; inset: 30% 25%; z-index: var(--z-modal); background: white; }
  .toast {
    position: fixed;
    right: 24%;
    bottom: 28%;
    z-index: var(--z-toast);
    background: #16a34a;
  }
</style>

<header class="header">Shop <nav class="dropdown">Menu</nav></header>
<section class="hero">Big sale</section>
<div class="modal">Sign in</div>
<div class="toast">Saved!</div>

Quick quiz 1 / 3

.card { opacity: 0.95; } contains .tip { position: absolute; z-index: 9999; }. The card's next sibling, .banner { position: relative; z-index: 1; }, overlaps it. What shows where they overlap?

Quick quiz 2 / 3

On which element does z-index: 5 have no effect?

Quick quiz 3 / 3

A card's ::before decoration with z-index: -1 disappears behind the card's background. What is the cleanest fix?

What to remember

  • z-index only works on positioned elements and on flex or grid items.
  • z-index is compared inside one stacking context, and the whole context moves as one layer in its parent.
  • Positioned elements with a z-index, fixed or sticky elements, opacity below 1, transforms, filters and isolation: isolate all create contexts.
  • Use one custom-property token scale instead of an arms race of ever bigger numbers.

CSS reference — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Z-Index | Thuta Learning