Reference · Intermediate

The dialog element

Present a focused modal or nonmodal dialog with a clear name, deliberate opening, contained interaction, close behavior, and focus return.

Published
Last checked

Definition

dialog represents a dialog box. Calling showModal() places it in the top layer and makes the rest of the document inert for ordinary interaction. Calling show() creates a nonmodal dialog. The element still needs an accessible name and an explicit opening control.

Minimal pattern

<button type="button" id="open-settings">Open settings</button>
<dialog aria-labelledby="settings-title">
  <h2 id="settings-title">Display settings</h2>
  <form method="dialog">
    <button value="cancel">Close</button>
  </form>
</dialog>

JavaScript connects the opener to showModal(). A form with method="dialog" can close the dialog and return a value without a network submission.

Focus behavior

When opened modally, focus should move to an appropriate element inside. When closed, focus returns to the control that opened it when that control still exists. Escape can create a close request; applications should not silently disable expected dismissal without a strong reason.

Decisions and trade-offs

Use a dialog only when the task requires a temporary new context. Inline content is simpler for ordinary explanations and validation. Never open a dialog merely on page load for nonessential promotion, and do not stack dialogs unless the workflow has been carefully designed and tested.

Accessibility

Name the dialog with a visible heading. Keep instructions and errors inside its reading order. Ensure the close action is visible and keyboard reachable. Backdrop styling must not be the only indication, and the dialog must fit at high zoom without trapping actions below the viewport.

Common failures

  • Focus remains behind a modal dialog.
  • Closing removes the dialog without returning focus.
  • The dialog has no programmatic name.
  • A custom overlay lets keyboard focus escape to hidden content.
  • A fixed-height dialog clips enlarged text or the close action.

Verification checklist

Open and close repeatedly by keyboard, pointer, Escape, and visible close control. Inspect name, role, modal state, initial focus, containment, and focus return. Test long errors, 200% zoom, a 320-pixel viewport, reduced motion, and screen reader reading order. Confirm background content is not operable while a modal dialog is open.