The Dialog Element: Modals, Focus Management, and the ShowModal API

Build accessible modals with the HTML dialog element: showModal vs show, the top layer, ::backdrop, Escape and cancel, form method=dialog, and focus.

Executive Summary: The <dialog> element, opened with showModal(), gives you a modal that renders in the browser’s top layer above everything else, makes the rest of the page inert, traps keyboard focus, closes on Escape, and returns a value from a form, all without a library. It has worked in every major browser since Safari 15.4 in March 2022. What it does not do for you is close on a backdrop click, lock page scrolling, or decide where focus should go, and those three details are where most implementations go wrong.
Modal dialog centered over a dimmed page with a close button

Modal dialogs are one of the most frequently broken patterns on the web. Custom implementations let Tab escape behind the overlay, forget to make the background invisible to screen readers, fail to close on Escape, lose focus when they close, and fight z-index wars with sticky headers. Accessible modal libraries exist precisely because getting all of this right by hand takes hundreds of lines.

The HTML dialog element is a built-in element for dialog boxes. Called with showModal(), it becomes a modal: the browser places it in the top layer, a rendering layer above all normal content and immune to z-index and overflow of ancestors; it shows a styleable ::backdrop; and it makes everything outside the dialog inert, so it cannot be clicked, focused or read by assistive technology. Called with show(), it opens as a non-modal dialog with none of those effects.

How do you build a minimal modal?

<button type="button" id="open-delete">Delete project</button>

<dialog id="confirm-delete" aria-labelledby="confirm-title">
  <h2 id="confirm-title">Delete "Q3 Roadmap"?</h2>
  <p>This removes the project and its 14 tasks. You cannot undo this.</p>
  <form method="dialog">
    <button value="cancel">Cancel</button>
    <button value="delete" class="danger">Delete project</button>
  </form>
</dialog>

<script>
  const dialog = document.getElementById("confirm-delete");
  document.getElementById("open-delete").addEventListener("click", () => dialog.showModal());

  dialog.addEventListener("close", () => {
    if (dialog.returnValue === "delete") {
      deleteProject();
    }
  });
</script>

That is a complete, accessible confirmation modal. A form with method="dialog" closes its dialog on submit instead of sending a request, and the value of the button that submitted it becomes dialog.returnValue. No click handlers on the buttons are needed.

What does showModal() give you?

Behavior showModal() show() open attribute
Rendered in the top layer Yes No No
::backdrop Yes No No
Rest of the page inert Yes No No
Escape closes it Yes No No
Moves focus into the dialog Yes Yes No
Exposed as a modal to screen readers Yes No No

Avoid toggling the open attribute directly. It shows the element but skips focus handling and all modal behavior, which brings back every problem the element was meant to solve. Use showModal() for modals, show() for non-modal panels, and close() to close either.

Where does focus go in a dialog?

When a dialog opens, the browser moves focus into it: to the first element with the autofocus attribute if there is one, otherwise to the first focusable element. That default is not always what you want. For the delete confirmation above, focus would land on “Cancel”, which is actually the safe choice for a destructive action. For a long dialog whose first focusable element is a link at the bottom, the screen would scroll and the user would miss the content.

Choose deliberately:

  • Destructive confirmations: focus the least destructive action, usually Cancel.
  • Forms: put autofocus on the first field.
  • Content-heavy dialogs: give the heading tabindex="-1" and autofocus, so screen readers start at the top and read the title.

When the dialog closes, focus should return to the element that opened it. Chromium and Firefox do this automatically when the dialog was opened with showModal(), but behavior has differed across browsers and frameworks that re-render the trigger break it anyway. Do it explicitly:

let opener = null;

function openDialog(dialog) {
  opener = document.activeElement;
  dialog.showModal();
}

dialog.addEventListener("close", () => {
  if (opener && document.contains(opener)) opener.focus();
});

How does Escape close a dialog?

Pressing Escape on a modal fires a cancel event, then closes the dialog and fires close. The returnValue stays as whatever it was before, so reset it when you open the dialog if you rely on it.

To protect unsaved work, you can stop the Escape key from closing the dialog by calling preventDefault() on cancel:

dialog.addEventListener("cancel", (event) => {
  if (formHasUnsavedChanges()) {
    event.preventDefault();
    showDiscardWarning();
  }
});

Use this sparingly. Escape is how keyboard users expect to leave a modal, and trapping it without explanation is disorienting. Also note that some browsers limit repeated cancellation, closing the dialog on a second Escape press, to stop pages from trapping users.

Closing on backdrop click

Clicking the ::backdrop does not close a dialog by default. The backdrop is not a separate element; clicks on it are reported with the dialog itself as the target. If the dialog has no padding and its content fills an inner wrapper, any click whose target is the dialog element must have landed on the backdrop: I cover ::backdrop and other generated boxes in pseudo-elements in practice.

<dialog id="settings" class="modal">
  <div class="modal__inner">...</div>
</dialog>

.modal { padding: 0; }
.modal__inner { padding: 1.5rem; }

dialog.addEventListener("click", (event) => {
  if (event.target === dialog) dialog.close("dismiss");
});

Only add light dismiss to dialogs where losing the content is harmless, such as a preview or a settings panel that saves as you go. For forms, an accidental click outside should not throw away input.

How do you lock page scroll behind a modal?

The page behind a modal can still scroll with the mouse wheel or touch, which looks broken. The dialog element does not prevent it, so toggle a class on the root element:

.modal-open { overflow: hidden; }

function openDialog(dialog) {
  document.documentElement.classList.add("modal-open");
  dialog.showModal();
}

dialog.addEventListener("close", () => {
  document.documentElement.classList.remove("modal-open");
});

On pages with a visible scrollbar, hiding it shifts the layout sideways. Add scrollbar-gutter: stable to the root, where supported, or compensate with padding equal to the scrollbar width.

Styling the dialog and backdrop

dialog {
  border: 0;
  border-radius: 12px;
  padding: 0;
  max-width: min(32rem, calc(100vw - 2rem));
  box-shadow: 0 20px 60px rgb(0 0 0 / 0.3);
}

dialog::backdrop {
  background: rgb(15 23 42 / 0.6);
}

dialog[open] {
  animation: dialog-in 180ms ease-out;
}

@keyframes dialog-in {
  from { opacity: 0; transform: translateY(8px) scale(0.98); }
}

@media (prefers-reduced-motion: reduce) {
  dialog[open] { animation: none; }
}

The browser centers modal dialogs by default with margin: auto inside a fixed, full-viewport box. Opening animations are easy, as above. Closing animations are harder, because the dialog switches to display: none immediately when it closes; you need to run the animation first and call close() when it ends. Because the dialog sits in the top layer, there is no z-index to manage at all.

Accessibility details

  • Name the dialog. Point aria-labelledby at its heading, so screen readers announce “Delete Q3 Roadmap, dialog” when it opens.
  • Use role="alertdialog" for urgent confirmations that interrupt the user, and add aria-describedby pointing at the message.
  • Always provide a visible close control. Escape is not discoverable for everyone, and touch users have no Escape key.
  • Keep modals for real interruptions. A cookie notice, a newsletter prompt or a tooltip should not be modal.
  • For non-modal regions you need to disable, the inert attribute is now supported in all major browsers since Firefox 112 shipped it in April 2023. It is useful for off-canvas menus and for the content behind a custom overlay.

Frequently Asked Questions

What is the difference between show() and showModal()?

showModal() opens the dialog as a modal: it renders in the top layer with a backdrop, makes the rest of the page inert, and closes on Escape. show() opens a non-modal dialog that sits in normal page flow and leaves the rest of the page interactive.

Is the HTML dialog element accessible?

Yes, when opened with showModal(). It traps focus, makes background content inert to assistive technology, exposes a modal dialog role and supports Escape. You still need to give it an accessible name with aria-labelledby and manage where focus goes when it opens and closes.

How do I close a dialog when clicking outside it?

Listen for click events on the dialog and close it when event.target is the dialog element itself. For this to work, remove the dialog’s padding and put the content in an inner wrapper, so clicks inside the content never target the dialog element directly.

Do I still need a modal library?

For most modals, no. The dialog element handles the top layer, inert background, focus trapping and Escape in every major browser. A library may still help with complex closing animations, nested modal stacks or framework-specific state management.

Let the platform handle the hard part

The dialog element solves the parts of modals that are easy to get wrong and hard to test: focus containment, an inert background and stacking. That leaves you with three deliberate choices, which are initial focus, light dismiss and scroll locking. Make those, name the dialog, and you have a better modal than most libraries shipped a few years ago. The confirmation buttons inside it use the same form semantics described in the accessible forms guide. For the full reference, see the MDN dialog reference and the dialog section of the HTML Standard. Related reading on this site: the Popover API and details and summary.

Originally posted on 11 July 2023 and post last modified on 11 July 2023

Accessibility Dialog Element Front-End Development HTML5 JavaScript Modal Dialogs

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *