Skip to content

The HTML dialog element: an accessible modal without a library

From the work/ 14 min read

showModal() already moves focus, makes the page inert, closes on Escape and draws a ::backdrop. Complete HTML and React code, tested in Chromium, plus what you still own.

  • JavaScript
  • React
In this article (8)
  1. What showModal() gives a modal with no extra JavaScript
  2. Focus, an inert page and closing with Escape
  3. Styling the dialog with ::backdrop
  4. Full example (HTML, and React with a ref)
  5. What you still own: the title and the close button
  6. Common mistakes
  7. Frequently asked questions
  8. Checklist

You do not need a library for an accessible modal: an HTML <dialog> opened with showModal() moves focus inside, makes the rest of the page inert, closes on Escape, renders above everything with its own ::backdrop and, when it closes, hands focus back to whatever had it. You still write the title and a close button.

This guide covers what the browser does according to MDN's <dialog> reference and the HTML Standard, a complete example in plain HTML and in React with useRef, and what we verified with Playwright in Chromium, including a detail about where focus goes on close that the usual one-liner glosses over.

What showModal() gives a modal with no extra JavaScript

<dialog> has been Baseline "widely available" since March 2022, per MDN. There are two ways to open one and only one of them is a modal: showModal() opens a modal dialog, while show() opens a non-modal one that leaves the rest of the page usable. With showModal() you get all of this for free:

  • The top layer. Per MDN's showModal() page, the dialog is displayed in the top layer, above every other element, with a ::backdrop pseudo-element behind it. No z-index fights.
  • An inert page. Everything except the dialog and its descendants becomes inert "as if the inert attribute is specified": no clicks, no focus. Only the containing document is blocked; if the dialog lives in an iframe, the outer page stays interactive.
  • Escape to close. Escape fires cancel, then close. With several modals open, only the last one shown closes.
  • Semantics. MDN notes that a <dialog> opened with showModal() implicitly has aria-modal="true", and its implicit role is dialog.
  • Forms that close it. A <form method="dialog"> inside closes the dialog on submit, sends nothing to a server, and puts the submitting button's value in returnValue.
what a modal library writes in JavaScriptwhat you needtypical library (JS)<dialog> + showModal()on top of everythingportal + z-indextop layerpage behindfocus trap + aria-hiddeninert, no codeEscapekeydown listenercancel, then closefocus on openfocus() by handautofocus or first controlfocus on closestore and restore itback to previous focusdimmed backgroundan extra div::backdropaccessible namearia-labelledbyaria-labelledby (yours)the same list, with no dependencythe dialog's name and its close button are still yours either way

Scroll the figure sideways to see all of it

A typical modal library builds that list in JavaScript: a portal, a focus trap, aria-hidden, a keyboard listener, an overlay. With <dialog> the browser does it. What it does not do is name the dialog or give it a visible close button. Those are still yours.

Focus, an inert page and closing with Escape

On open. The standard defines the "dialog focusing steps": if the <dialog> itself has autofocus, focus the dialog; otherwise use its focus delegate (the descendant with autofocus or, failing that, the first focusable element in document order); and if there is none, focus the dialog. MDN recommends autofocus on the control the user will use first. In our test, a dialog holding only text focused itself.

On close. This is the detail. The usual line is "focus returns to the button that opened it," and that is not quite what the standard says. show() and showModal() store the element that had focus right before opening (the "previously focused element"). On close, the browser focuses that element again if the dialog was modal or focus was inside it, without scrolling. MDN's <dialog> reference does not describe this step; MDN's ARIA dialog role page asks for the same outcome: move focus back to where it was before it entered the dialog. In practice:

  • When the user clicks the button and the browser focuses it, focus returns to the button. That is what happened in Chromium 151.
  • When you open the modal from code, say on a timer, focus returns to whatever was focused at that moment. In our test it went back to the search box, not to any button.
  • When the button was removed while the modal was open, there is nothing to return to and focus falls to body.
  • MDN's <button> page notes that Safari, by design, does not focus a button when you click it. There, the stored element is whatever had focus before the click. We did not test Safari.

The page behind. While the modal is open, the page behind does not respond. We checked: calling focus() on a background button left focus where it was, and a real click at its coordinates landed on the dialog (elementFromPoint returned the <dialog>). With Tab, focus went Cancel, Remove, out of the document (document.activeElement became body) and back to Cancel, never reaching the cart.

Escape. A close request fires cancel, which preventDefault() can cancel, and then close. Per MDN's cancel event page, close requests can come from Escape on desktop, requestClose() and the back button on mobile. close() skips cancel and cannot be stopped. requestClose() is newer: Baseline since May 2025. A dialog opened with show() does not close on Escape.

BehaviorshowModal()show()
Top layer and ::backdropYesNo
Rest of the page inertYesNo: the page behind stays focusable and clickable
Escape closes itYes: cancel, then closeNo
Focus on openDialog focusing stepsThe same steps
Focus on closeTo the element that had focus before openingTo the same element, only if focus was inside
Matches :modalYesNo
Implicit aria-modaltruefalse
showModal() against show(), behavior by behaviorbehaviorshowModal()show()top layer + ::backdropyesnorest of the page inertyesnoEscape (cancel → close)yesnofocus on openautofocus › first › dialogthe same stepsfocus on closewhatever had focus beforeif focus is insidematches :modalyesnoimplicit aria-modaltruefalseonly the modal one makes the page inertclosedby="any" (click outside): Chrome/Edge 134+, Firefox 141+, Safari only in Preview

Scroll the figure sideways to see all of it

Neither closes on a click outside by default. That is what the closedby="any" attribute is for, but MDN's closedBy page marks it as limited availability: MDN's compatibility data lists Chrome and Edge 134, Firefox 141, and Safari only in Technology Preview, not on iOS. In Chromium 151, a click on the backdrop closed the dialog with closedby="any" and did nothing without it.

Styling the dialog with ::backdrop

::backdrop is a viewport-sized box rendered right beneath the element in the top layer, and it only exists when you open with showModal(). These are the example's three rules:

dialog { max-width: min(28rem, calc(100% - 2rem)); padding: 1.5rem; border: 1px solid #d4d4d4; border-radius: 12px; }
dialog::backdrop { background: rgb(0 0 0 / 0.55); }
html:has(dialog:modal) { overflow: hidden; }
  1. The dialog box: a 28rem max width that never touches the edges on a phone, padding and a border. Do not set display here: in our test, dialog { display: flex; } made a closed dialog visible, because it overrides the browser's display: none. If you need flex, use dialog[open].
  2. The layer that dims the page. Since the page is already inert, the ::backdrop is purely visual.
  3. Stops the page from scrolling while a modal is open. You need it, because the dialog does not do it: without this rule, with the modal open, the mouse wheel moved the page 800 px and Page Down another 525; with it, 0. :has() has been Baseline since December 2023 and :modal since September 2022, per MDN.

Full example (HTML, and React with a ref)

The scenario: a cart with a Remove button that asks for confirmation. It covers what matters: an accessible name, initial focus, returnValue, and focus when the opening button disappears. This is the whole file, with no dependencies:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Your cart</title>
  <style>
    dialog { max-width: min(28rem, calc(100% - 2rem)); padding: 1.5rem; border: 1px solid #d4d4d4; border-radius: 12px; }
    dialog::backdrop { background: rgb(0 0 0 / 0.55); }
    html:has(dialog:modal) { overflow: hidden; }
  </style>
</head>
<body>
  <h1 id="cart-title" tabindex="-1">Your cart</h1>
  <ul id="cart">
    <li id="item-1">Runner sneakers, size 9
      <button type="button" class="remove" data-item="item-1">Remove</button>
    </li>
  </ul>

  <dialog id="confirm-remove" aria-labelledby="confirm-title">
    <form method="dialog">
      <h2 id="confirm-title">Remove this item from your cart?</h2>
      <p>You can add it back later.</p>
      <button value="cancel" autofocus>Cancel</button>
      <button value="remove">Remove</button>
    </form>
  </dialog>

  <script>
    const dialog = document.getElementById("confirm-remove");
    let pending = null;

    document.getElementById("cart").addEventListener("click", (event) => {
      const button = event.target.closest(".remove");
      if (!button) return;
      pending = document.getElementById(button.dataset.item);
      dialog.returnValue = "";
      dialog.showModal();
    });

    dialog.addEventListener("close", () => {
      if (dialog.returnValue === "remove") {
        pending.remove();
        document.getElementById("cart-title").focus();
      }
      pending = null;
    });
  </script>
</body>
</html>
  1. The <style> block holds the three rules from the previous section.
  2. The h1 has tabindex="-1" so the script can focus it without adding it to the Tab order.
  3. Each Remove button is type="button" and names the row it deletes with data-item.
  4. The <dialog> has aria-labelledby="confirm-title", so its accessible name is the h2 text.
  5. The <form method="dialog"> wraps the content. Both buttons default to submit, so either one closes the dialog and leaves its value in returnValue.
  6. autofocus is on Cancel, the safe choice: a user who hits Enter without reading deletes nothing.
  7. One listener on the ul handles every button through closest(".remove"), stores the row in pending, clears returnValue and opens with showModal().
  8. Clearing returnValue matters: per the standard and MDN's returnValue page, Escape does not change it, so the "remove" from a previous confirmation could linger. MDN's own example does the same before each open.
  9. The close event always fires, however the dialog closes. If the answer was "remove", it deletes the row.
  10. The browser has already sent focus back to Remove, but that button goes away with the row. Without the focus() call on the h1, focus would fall to body.

In React the idea is the same: a ref to the <dialog> and the browser's own methods. The component uses useRef and onClick, so in Next.js it needs "use client"; if you are unsure where that goes, see where to put the use client boundary in Next.js.

"use client";

import { useId, useRef, useState } from "react";

function RemoveButton({ name, onRemove }: { name: string; onRemove: () => void }) {
  const dialogRef = useRef<HTMLDialogElement>(null);
  const titleId = useId();

  function open() {
    const dialog = dialogRef.current;
    if (!dialog) return;
    dialog.returnValue = "";
    dialog.showModal();
  }

  function handleClose() {
    if (dialogRef.current?.returnValue === "remove") onRemove();
  }

  return (
    <>
      <button type="button" onClick={open}>Remove</button>
      <dialog ref={dialogRef} aria-labelledby={titleId} onClose={handleClose}>
        <form method="dialog">
          <h2 id={titleId}>Remove {name} from your cart?</h2>
          <p>You can add it back later.</p>
          <button value="cancel">Cancel</button>
          <button value="remove">Remove</button>
        </form>
      </dialog>
    </>
  );
}

export function Cart() {
  const [items, setItems] = useState([{ id: "1", name: "Runner sneakers, size 9" }]);
  const headingRef = useRef<HTMLHeadingElement>(null);

  function remove(id: string) {
    setItems((list) => list.filter((item) => item.id !== id));
    headingRef.current?.focus();
  }

  return (
    <section>
      <h1 ref={headingRef} tabIndex={-1}>Your cart</h1>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            {item.name} <RemoveButton name={item.name} onRemove={() => remove(item.id)} />
          </li>
        ))}
      </ul>
    </section>
  );
}
  1. "use client" marks the file as a Client Component in Next.js; outside Next.js it does nothing.
  2. dialogRef points at the <dialog>, and useId() makes a unique id for the title, because every cart row has its own dialog.
  3. open() clears returnValue and calls showModal(). There is no isOpen state: the browser already knows whether it is open.
  4. onClose is the browser's close event, which React exposes for <dialog> per its common components reference. That is where returnValue is read.
  5. Cancel comes first on purpose and has no autoFocus. React focuses an autoFocus element "on mount," while the dialog is still closed, and in our test React 19.0.0 did not write the autofocus attribute to the DOM, so on open the browser focused the first button. If you need a different control, call its focus() after showModal().
  6. Cart deletes the item and moves focus to the h1, as in the HTML version, because the row and its button go away.

Do not use <dialog open={isOpen}>: the open attribute opens a non-modal dialog. In our test it was open but did not match :modal: a non-modal dialog, with no inert page and no Escape to close it. If you would rather drive it from state, an effect that calls showModal() and close() is a legitimate use (syncing with a browser API), unlike derived state in useEffect.

We ran both examples with Playwright 1.62 in Chromium 151, in English and Spanish: 72 checks, all green. These are six lines from the English HTML run:

PASS  focus moved inside the dialog (autofocus button)  (button:Cancel)
PASS  click on the background button does nothing  (elementFromPoint -> #confirm-remove)
PASS  Escape fires cancel, then close  (cancel(cancelable=true),close)
PASS  focus back on the opener (it had focus when showModal ran)  (button:Remove)
PASS  form method="dialog": returnValue is the button value  (remove)
PASS  programmatic open: focus returns to the previously focused #search  (input#search)
  1. On open, focus is on Cancel, the autofocus button.
  2. A click on the Remove button behind lands on the <dialog>.
  3. Escape: cancel (cancelable), then close.
  4. Focus returns to Remove, which had it when showModal() ran.
  5. Remove, inside the dialog, leaves "remove" in returnValue.
  6. On another page, a modal opened from code gave focus back to the search box.

What you still own: the title and the close button

The name. The browser exposes <dialog> with the dialog role, but it does not make up a name. MDN's dialog role page strongly recommends one and suggests aria-labelledby pointing at the visible title, plus aria-describedby for any text that explains it. With no visible title, use aria-label.

The close button. Escape is not a visible control, and a phone has no Escape key. Always include a real <button> that closes: Cancel in a confirmation, Close in an informational modal. If it is an icon, name it with aria-label="Close". If the form has required fields, the cancel button needs formnovalidate or a close() call: MDN explains that otherwise validation will not let the dialog close.

the parts of a modal built with <dialog>::backdropRemove this item?<form method="dialog">CancelRemovevalue="cancel" · value="remove"dialog::backdropcovers the page, which goes inertaria-labelledby="confirm-title"the h2 gives the dialog its name<form method="dialog">a button closes it, sets returnValueautofocusgets focus when it opensthe browser puts it in the top layeryou add the name (aria-labelledby) and a visible close button

Scroll the figure sideways to see all of it

And do not put tabindex on the <dialog>: both MDN and the standard forbid it. If the modal holds a form, say an email capture or an address, the same rules apply as in mobile checkout autocomplete and keyboards: autocomplete, type and inputmode decide whether the shopper types it in one tap or in a minute.

Common mistakes

  • Opening with the open attribute (or <dialog open> in React). MDN advises against it: the dialog is non-modal.
  • Using show() for a modal. show() is non-modal: the page behind stays live and Escape does not close it.
  • Assuming focus returns to the button. It returns to whatever had focus at open. If you open from code, or the button disappears, decide where focus goes yourself.
  • Not resetting returnValue. The previous answer can leak past an Escape. Chromium 151 showed "", but the standard does not promise that: reset it before every showModal().
  • Relying on React's autoFocus. It focuses on mount, while the dialog is closed.
  • Setting display on the dialog selector. The closed dialog becomes visible. Use dialog[open].
  • Forgetting background scroll. The page keeps scrolling under the modal until you add overflow: hidden.
  • Always blocking Escape. Calling preventDefault() on every cancel leaves keyboard users with no way out. Keep it for unsaved-changes warnings.

Frequently asked questions

Do I need a focus trap for an HTML dialog modal?

No. With showModal() the rest of the document is inert, so Tab only moves through the dialog's controls and then out of the page to the browser. In our test it never reached an element of the page behind.

How do I close it on a click outside?

With closedby="any", in browsers that support it: Chrome and Edge 134 or later and Firefox 141 or later, per MDN's data; Safari only has it in Technology Preview. Elsewhere, a click outside does nothing. Accessibility does not depend on it: Escape and a visible button are enough.

Do I need role="dialog" or aria-modal="true"?

No. The implicit role of <dialog> is dialog, and MDN notes that a dialog opened with showModal() implicitly has aria-modal="true". What you do need to add is the name, with aria-labelledby or aria-label.

Does it work in every browser?

<dialog>, showModal(), close() and ::backdrop have been Baseline since March 2022. requestClose() since May 2025. closedby still has limited availability, so treat it as an optional enhancement.

Checklist

  • You open with showModal(), not show() or the open attribute.
  • The <dialog> has a name: aria-labelledby pointing at the visible title, or aria-label.
  • There is a visible close button, with text or an aria-label.
  • autofocus sits on the control the user needs first; in a confirmation, the safe option.
  • Form buttons use method="dialog" with distinct values, and you reset returnValue before opening.
  • If the button that opened the modal can disappear, you move focus somewhere sensible on close.
  • The background is styled with ::backdrop and does not scroll: html:has(dialog:modal) { overflow: hidden; }.
  • There is no tabindex on the <dialog> and no display on the dialog selector.
  • You tested it with the keyboard: Tab, Escape, and where focus lands.

With that, the modal does what your library did, with zero dependencies. If the modal collects data, also read how to set up autocomplete and keyboards in a mobile checkout. And if you are building it in React, skip the effects you do not need: compute derived state during render.

Saw this on Instagram? Comment DIALOG on the Reel and I'll send you the guide.

Written by

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published November 3, 2026

← Blog