← Tous les articles

CSS: why z-index is not working (stacking context)

A z-index: 9999 that stays under another element? Not a bug: a stacking context. How to spot it and fix it.

CSS: why z-index is not working (stacking context)

Key points

  • z-index only compares elements within the same stacking context.
  • transform, opacity, filter or position: fixed create a new context.
  • The fix is often to move the element or drop the property that creates the context.

The dropdown slides under the header image despite z-index: 9999. A bigger number will not help: the element is trapped in a stacking context.

The idea

A stacking context is a box inside which z-index values are compared. A child with z-index: 9999 can never rise above something outside its parent if that parent sits lower. Think of a sheet at the bottom of a drawer: it stays in the drawer.

What creates a context (often by accident)

  • position relative or absolute with a z-index.
  • position: fixed or sticky.
  • transform, filter, backdrop-filter, perspective.
  • opacity below 1.
  • isolation: isolate, will-change, contain.

The typical case

A header with an entrance animation (transform) and a dropdown inside. The next section, later in the HTML, paints on top. Fix:

.site-header { position: relative; z-index: 50; } /* the whole header comes forward */
/* or remove the transform once the animation ends */

A z-index scale

On our projects we define a few levels as variables instead of random numbers:

:root { --z-dropdown: 20; --z-header: 50; --z-modal: 100; --z-toast: 110; }

Modals are placed directly in body so no parent context can trap them.

FAQ

How can I see stacking contexts?

Chrome DevTools’ Layers panel and some extensions show them. Otherwise walk up the parents looking for transform, opacity or position fixed.

What is isolation: isolate for?

To create a context on purpose so a component cannot interfere with the rest of the page.

Facing this on your site or app? We diagnose and fix it.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →