🍋
Menu
Troubleshooting Beginner 1 min read 251 words

Troubleshooting CSS Z-Index Stacking Issues

Z-index doesn't always work as expected because of stacking contexts. Learn how stacking contexts are created, how they affect z-index, and how to debug layering issues.

The Z-Index Mental Model

Z-index only works on positioned elements (position: relative/absolute/fixed/sticky) and flex/grid children. More importantly, z-index creates a stacking context — a self-contained layer that contains all of its children. Children cannot escape their parent's stacking context, no matter how high their z-index.

What Creates a Stacking Context

Beyond positioned elements with z-index, these CSS properties create new stacking contexts: opacity less than 1, transform (any value), filter, backdrop-filter, perspective, clip-path, will-change, contain (layout or paint), and isolation: isolate. This means a seemingly unrelated property like opacity: 0.99 can break your carefully planned z-index hierarchy.

Debugging Steps

First, identify which stacking contexts exist. In Chrome DevTools, the Layers panel shows 3D stacking contexts. Check if your element's parent has any of the stacking-context-creating properties. Remember: a child element with z-index: 9999 inside a parent with z-index: 1 will still be below a sibling element with z-index: 2.

Common Patterns and Fixes

For overlapping modals and dropdowns, use a single stacking context at the body level for all overlays. For header/sticky elements overlapping content, ensure the header's stacking context contains an appropriate z-index relative to the main content area. Use CSS custom properties to manage z-index values systematically:

:root {
  --z-dropdown: 100;
  --z-sticky: 200;
  --z-modal: 300;
  --z-toast: 400;
}

The Isolation Property

isolation: isolate creates a new stacking context without requiring z-index or transform. Use it intentionally to contain component z-index values within their own context, preventing them from interfering with other components.

Herramientas relacionadas

Formatos relacionados

Guías relacionadas