z-index: 99999 Not Working? Your Modal Is Trapped
October 8, 2026 | 9 min read | CSS
By Syed · Frontend Engineer & Creator of UITweak
You set z-index: 99999 on the modal. It still renders behind the sticky header. You try 999999. Still behind. The number was never the problem: your modal is trapped inside a stacking context, and z-index only orders elements within the same context. A modal at z-index: 99999 inside a trapped parent loses to a header at z-index: 10outside of it, every time. The fix is not a bigger number. It is getting the modal out of the trap, and the platform now gives you three clean escapes.
30-second version: z-index only competes inside one stacking context. Something above your modal (a transform, filter, opacity, positioned parent with z-index) sealed it in. Escape with <dialog>.showModal() (top layer, no z-index needed), the popover API for non-modal overlays, or a React portal to document.body. Diagnose first with the DevTools Layers panel.
Why z-index: 99999 Did Nothing
Think of stacking contexts as sealed rooms. Inside a room, z-index decides who stands in front. But no one inside any room can ever step in front of someone standing outside the building the room is in. Your modal and your header are in different rooms, so their z-index values never meet.
The five accidental room-builders to memorize:
- A positioned element (
relative,absolute,fixed,sticky) with anyz-indexother thanauto. transformset to anything butnone(the classic: a parent withtransform: translateZ(0)for a perf hack).filter,perspective,clip-path,mask.opacityless than 1,mix-blend-modeother than normal.will-changeorcontain: layout/painton the parent.
The usual crime scene: a modal component nested three levels deep inside a card that has transform: translateY(0) from an entrance animation. The modal can never escape that card no matter what number you type.
Find the Trap: The DevTools Layers Panel
Stop guessing. In Chrome DevTools, open More tools → Layers. It draws every stacking context as a separate layer in 3D. Find your modal in the tree, then look upward: the first ancestor that appears as its own layer is the room your modal is sealed in. Click it and DevTools tells you which property created the context.
Faster check when you already suspect the culprit: select the modal in Elements, then walk up the ancestors in the DOM tree watching the Computed tab for transform, filter, or opacity. The first ancestor carrying one of them is usually your trap.
Escape 1: <dialog> and the Top Layer
The cleanest escape. Calling showModal() on a <dialog> promotes it to the top layer: a browser-managed plane above all page content where z-index, overflow, and transforms simply do not apply. No z-index needed at all, and you get a free ::backdrop:
<dialog id="confirm">
<h2>Delete this project?</h2>
<button id="cancel">Cancel</button>
<button id="ok">Delete</button>
</dialog>
<script>
const d = document.getElementById("confirm");
document.getElementById("open").onclick = () => d.showModal();
document.getElementById("cancel").onclick = () => d.close();
</script>/* the backdrop is free: style it */
dialog::backdrop {
background: rgb(0 0 0 / 0.5);
backdrop-filter: blur(2px);
}One caveat on that backdrop-filter: Safari still has quirks with it (prefix, edge cases), covered in our Safari backdrop-filter troubleshooting guide.
Note the method matters: showModal() uses the top layer, while show() renders the dialog inline like a normal element (still trapped). If your dialog is behind things, check you called the right one. <dialog> is Baseline widely available, so this is the default answer for true modals in 2026.
Escape 2: The Popover API for Non-Modal Overlays
Not everything is a modal. Dropdown menus, toasts, teaching tips, and action menus should not trap focus, but they still need to escape stacking contexts. The popover API puts any element in the top layer declaratively, with light-dismiss and Escape handling built in:
<button popovertarget="menu">Account</button>
<div id="menu" popover="auto">
<a href="/profile">Profile</a>
<a href="/settings">Settings</a>
<button>Sign out</button>
</div>popover="auto" gives you top-layer rendering, click-outside dismissal, and Escape for free, with zero JavaScript. Use popover="manual" when you want to control dismissal yourself. Support is Baseline 2025: Chrome 114+, Edge 114+, Firefox 125+, Safari 17+. Rule of thumb: <dialog> when the user must decide before continuing, popover when the rest of the page stays usable.
Escape 3: Portal to document.body (React/Next)
In React, the modal usually lives deep in the component tree, inheriting every ancestor's stacking context. createPortal renders it as a direct child of document.body instead, which escapes all of those contexts at once:
import { createPortal } from "react-dom";
function Modal({ open, onClose, children }) {
if (!open) return null;
return createPortal(
<div className="fixed inset-0 z-50 grid place-items-center">
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
<div className="relative bg-white rounded-2xl p-6">{children}</div>
</div>,
document.body
);
}The trap inside the trap: this only works if document.body itself has no transformed ancestors above the portal target. If your app root wrapper carries a transform or filter, even a body-level portal is sealed in, and position: fixed positions relative to that ancestor instead of the viewport. Keep transforms off your root containers, or use Escape 1 and let the top layer handle it.
Gotcha: Fullscreen Is Top Layer Too
One more room most people forget: the Fullscreen API. A fullscreen element also lives in the top layer, and it sits above dialogs opened afterward. A production report from September 2026 described a dialog going invisible because it was opened while a video element held fullscreen. The practical rule: do not open dialogs while anything is fullscreen. Exit fullscreen first, then open the dialog.
Decision Tree + Recap
- Modal renders behind things despite a huge z-index? You are in a stacking-context trap. Confirm with the DevTools Layers panel.
- True modal (user must decide)? Use
<dialog>+showModal(). Top layer, free backdrop, no z-index. - Non-modal overlay (menu, toast, tip)? Use
popover="auto". Top layer plus light-dismiss, no JavaScript. - Stuck in React component tree?
createPortaltodocument.body, and keep transforms off your root containers. - Memorize the five trap-builders: positioned+z-index,
transform,filter/perspective,opacity< 1,will-change/contain.
Related: once your modal escapes, its shadow still needs to look right. Our box-shadow cut-off fix guide covers shadows clipped by overflow: hidden ancestors, the other half of the trapped-overlay story.
The Full Trap-Builder List
The main guide named five context-builders. Here is the rest you will meet in real codebases. Flex and grid children with any z-index other than auto create a stacking context even without position. isolation: isolate creates one on purpose, which is useful for blend modes but seals children in all the same. backdrop-filter seals like filter does. contain: layout or paint seals the element. column-span: all seals it. And sticky or fixed positioning combined with a z-index seals it, which is why sticky headers are such common modal-blockers. I keep this list in my head as a single question: which ancestor did I stop thinking about? The culprit is almost always one of these, sitting on a wrapper added months ago for a different reason.
position: fixed Breaks Inside Transformed Ancestors
Related trap, different symptom: a fixed overlay that scrolls with the page. Any ancestor with a transform other than none becomes the containing block for fixed descendants, so fixed stops meaning viewport-fixed. filter and perspective do the same. The classic crime scene is a translateZ(0) added years ago as a perf hack on a page wrapper. The fix is structural: move the overlay out from under the transformed ancestor, or promote it to the top layer with dialog or popover, where containing-block games do not apply. If you cannot move it, remove the transform. That perf hack is rarely load-bearing in 2026, and it is holding your overlay hostage.
/* the trap: a "harmless" perf hack on a wrapper */
.page {
transform: translateZ(0);
}
/* this modal now positions against .page, not the viewport */
.modal {
position: fixed;
inset: 0;
}Stacking Inside the Top Layer
Open two dialogs and they stack in the order they were added: the later showModal() paints on top. Popovers behave the same. This stays predictable until you close them out of order. Closing the bottom dialog leaves the top one in place, which is correct but confuses state machines that assume a single modal. Plan for it: track open dialogs in a stack, not a boolean. One more behavior to know before you rely on dialog: showModal() makes the rest of the page inert. Background clicks do nothing, keyboard focus cannot leave the dialog, and screen readers skip the page behind it. That is free focus trapping, and it is also a commitment: nothing behind the dialog is reachable until it closes. It does not lock body scroll, though. The page behind a modal dialog still scrolls under your finger on touch devices unless you set overflow: hidden yourself.
The Scroll-Lock Recipe
Opening a modal without locking scroll produces two bugs. The background scrolls under the overlay on touch, and hiding the scrollbar shifts the layout sideways on desktop. The minimal fix is overflow: hidden on the body while the modal is open, restored on close, managed in a React effect or a tiny open/close helper so it cannot leak. The sideways shift has a permanent fix: scrollbar-gutter: stable on the root reserves scrollbar space at all times, so showing or hiding the scrollbar changes nothing. I set scrollbar-gutter: stable globally on every project now. It costs nothing and deletes a whole class of shift bugs, modal-related or not.
useEffect(() => {
if (!open) return;
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.body.style.overflow = prev;
};
}, [open ]);/* reserve scrollbar space permanently: no more sideways jumps */
:root {
scrollbar-gutter: stable;
}React: Portal Plus Native Dialog
The most robust React modal combines two escapes from the main guide: createPortal to document.body plus a real dialog element driven by showModal(). The portal escapes the component tree's stacking contexts. The dialog gets the top layer, the inert background, and Escape handling. Wire it with a ref and effects: call showModal() when open flips true and close() when it flips false, guard the portal behind a mounted flag so document.body is never touched during server render, and listen for the cancel event (fired on Escape) to route closing through onClose instead of letting the dialog close itself. That keeps React state as the single source of truth. For backdrop clicks, compare e.target to e.currentTarget in the dialog's click handler: a backdrop click targets the dialog element itself.
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
function Dialog({ open, onClose, children }) {
const ref = useRef(null);
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
useEffect(() => {
const el = ref.current;
if (!el) return;
if (open && !el.open) el.showModal();
if (!open && el.open) el.close();
}, [open ]);
useEffect(() => {
const el = ref.current;
if (!el) return;
const onCancel = (e) => {
e.preventDefault();
onClose();
};
el.addEventListener("cancel", onCancel);
return () => el.removeEventListener("cancel", onCancel);
}, [onClose]);
if (!mounted) return null;
return createPortal(
<dialog
ref={ref}
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
{children}
</dialog>,
document.body
);
}Stop the Arms Race: A z-index Scale
When z-index values scatter across files, every new overlay restarts the bidding war. The architectural fix is a single scale of named tokens on :root: base, sticky, dropdown, modal, toast. Every component uses a token. New layers get a token added to the scale, never a bigger number typed into a component file. Review becomes trivial: the scale is the whole story, in one place. And adopting dialog and popover shrinks the scale, because top-layer elements need no z-index at all. The scale then covers only positioned page content. My preferred order: top layer first for anything overlay-like, tokens for whatever remains in normal flow.
:root {
--z-base: 1;
--z-sticky: 10;
--z-dropdown: 20;
--z-modal: 30;
--z-toast: 40;
}
.site-header {
z-index: var(--z-sticky);
}Focus Management: The Part Everyone Skips
showModal() traps focus inside the dialog, but it does not decide where focus starts or where it goes when the dialog closes. Left alone, focus lands on the first focusable element, which is often fine, and on close it drops to document.body, which is not. The pattern I use: before calling showModal(), store the element that triggered it; on close, hand focus back to that trigger. For where focus starts, the autofocus attribute fires when the dialog opens, so put it on the primary action. One deliberate choice for destructive confirmations: focus the safe button first, not the delete button. Keyboard users tab in order, and the first focused control should never be the irreversible one.
const trigger = document.activeElement;
dialog.showModal();
// later, on close:
dialog.addEventListener("close", () => trigger.focus(), { once: true });Frequently Asked Questions
Is there a maximum z-index?
The maximum is 2147483647 (a 32-bit signed integer), but it never matters. If z-index: 99999 fails, z-index: 2147483647 fails identically, because the trap is the stacking context, not the number. Fix the context, not the digits.
Does the top layer respect z-index at all?
Elements in the top layer stack in the order they were added, above all regular page content. Between two top-layer elements, the later one paints on top. Regular z-index values do not reach into the top layer.
Can I animate a dialog open and close?
Yes, with @starting-style and transition-behavior: allow-discrete for the enter animation, plus a closing class for exit. The display flip from none is the part that needs the discrete-transition treatment.
Which browsers support the popover API?
Baseline 2025: Chrome 114+, Edge 114+, Firefox 125+ (April 2024), Safari 17+ (September 2023), iOS Safari 17+. For older browsers, keep a createPortal fallback or a tiny polyfill on the same trigger.
Try it: related UI elements
Delete item?
This action cannot be undone. The item will be permanently removed.
Modal Dialog
Copy code →
Command Palette
Copy code →
Sunset over the ridge, edited in Lightroom
Image Lightbox
Copy code →
Popular
Fullscreen Search Overlay
Copy code →