Lesson 20: Dialog

The <dialog> tag gives you a clean way to build popups and dialog windows in HTML.

A modal dialog sits on top of all other page content. It puts a backdrop underneath and blocks the rest of the page so the user has to interact with the dialog.

You can open and close dialogs using JavaScript methods. There are simple commands to show the dialog as a modal or a non-modal popup, and another command to close it.

When you open a dialog as a modal, the browser blocks clicks and keyboard events outside the popup. Focus moves inside the dialog automatically, and users can only tab between the items inside the popup.

Avoid opening dialogs automatically without a user action. If you show a popup, make sure the focus goes back to where the user was when the dialog closes.

You can style the backdrop behind the modal using CSS.

Non-modal dialogs

A non-modal dialog is a popup that doesn’t block the rest of the page. The user can still click and interact with other links while the popup is open. The Escape key doesn’t close non-modal dialogs by default, so you must include a close button.

Closing a dialog

You can close a dialog without writing any scripts. If you put a form inside the dialog and set its method attribute to "dialog", submitting the form closes the dialog automatically.

<dialog>
  <form method="dialog">
    <button type="submit">Close</button>
  </form>
</dialog>

When you submit this form, the browser closes the dialog but keeps any data the user typed. It does not send the data to a server.

You can add the autofocus attribute to the close button so it gets selected as soon as the dialog opens. Think carefully before using autofocus because it can make it harder for keyboard users to navigate.

If you add the open attribute directly to the <dialog> tag in your HTML, the dialog will show up open when the page loads. This creates a non-modal dialog. Using scripts to open dialogs is usually better.

Accessibility and styling

Don’t add focus settings directly to the <dialog> tag. Only the interactive items inside the dialog should get focus.

You should also link the dialog to a heading using aria-labelledby to give it a clear name for screen readers.

Keep in mind that browsers have different default styles for dialog colors and backgrounds. You should define these explicitly in your CSS.


Adapted from Learn HTML © Google and contributors, licensed under CC BY 4.0 (prose) and Apache 2.0 (code samples).