DOM & Events

<dialog> Element and Native Top Layer

HTML primitive placing modals in the browser Top Layer above any z-index, with built-in focus management and Escape key handling.

About this page
READ
2 min
BASELINE
Baseline · Widely available
Interactive Simulator

Modal: Portal + Focus-Trap vs <dialog>

Lines of Code
Before
45
After
6
Reflows / Browser Cost
Before
Body mutation
After
Isolated Top Layer
BeforeDiv + React Portal + focus-trap
<Portal>
  <div role="dialog" aria-modal="true"
       style={{ zIndex: 9999 }}>
    {/* + Escape listener + focus trap */}
  </div>
</Portal>
Lines: 45Reflows: Body mutationDependencies: focus-trap (~8 kB)

Remains vulnerable to z-index conflicts across portals.

After (Native)Native <dialog>.showModal()
<dialog ref={ref}>
  <form method="dialog">
    <button>Close</button>
  </form>
</dialog>
// ref.current.showModal()
Lines: 6Reflows: Isolated Top LayerDependencies: 0 kB

Inertness, Escape, and ::backdrop handled by the engine.

Live DOM Sandbox:

Rendered in the browser Top Layer with native Escape and inert background.

Modal: Portal + Focus-Trap vs <dialog>

Under the Hood#

  1. dialog.showModal() appends the element to the Document internal top layer list, painted after the root CSS Stacking Context.
  2. The engine generates a ::backdrop pseudo-element immediately beneath the dialog inside the same Top Layer.
  3. Every node outside the dialog is marked inert: pointer clicks, text selection, and keyboard tabbing are blocked natively without global listeners.
HTML
<dialog id="confirm-modal">
  <p>Delete production index?</p>
  <form method="dialog">
    <button value="cancel">Cancel</button>
    <button value="confirm">Confirm</button>
  </form>
</dialog>
<script>
  document.getElementById('confirm-modal').showModal();
</script>

Problem Genealogy#

  • 2012 (React Portals + z-index: 9999): Moving modals manually to document.body to escape overflow: hidden, a ceremony that only existed because CSS lacked a real Top Layer.
  • 2018 (focus-trap + manual aria-hidden): Fragile JS boilerplate to trap Tab navigation and hide background nodes from screen readers.
  • 2022+ (<dialog> Baseline): Top Layer, ::backdrop, inert, and Escape dismissal built directly into the engine.

Production Pitfalls#

  • Calling .show() instead of .showModal(): .show() activates neither the Top Layer, nor ::backdrop, nor background inertness, leaving your modal trapped in the same z-index swamp you were trying to escape.
  • Exit animations: dialog.close() switches immediately to display: none; combine @starting-style with transition-behavior: allow-discrete to animate exits.

Where this connects

Next & related

Rendering Pipeline

CSS Stacking Context

The Top Layer bypasses the entire stacking context hierarchy and overflow: hidden clipping.

Mechanical Comparisons