Favorites

Using the <dialog> Element for Native Modals

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
dialog modals

For years, developers reached for JavaScript libraries, such as Bootstrap, home-made overlays or npm packages, whenever they needed a modal. There was never a shortage of options, but every one came with trade-offs: too heavy, too hard to style, or quietly broken for keyboard and screen reader users. Managing focus alone could take an afternoon.

That changed when the <dialog> element gained support in all major browsers in 2022. Today it's the native, accessible, dependency-free way to build modals, alerts and drawers. The browser handles stacking, the backdrop, keeping focus inside the dialog, and closing with the Esc key: things that used to take hundreds of lines of JavaScript.

This post walks through everything you need to use it confidently, with a live demo in each section.

What is <dialog>?

The <dialog> element represents a dialog box: an alert, a confirmation prompt, a form, or any other panel that appears over the page. It's either open or closed, and you control it with three JavaScript methods:

// Modal: blocks the rest of the page and adds a backdrop
dialog.showModal();

// Non-modal: floats above the page without blocking it
dialog.show();

// Close, optionally passing a return value
dialog.close('confirmed');

What makes it better than a <div> with some CSS? The browser gives it real meaning for assistive technology, and a modal dialog is placed in the top layer, a special layer above everything else on the page, so it always appears on top, whatever the z-index of other elements. It also gets built-in behaviour such as closing with Esc.

Opening a dialog without JavaScript

With invoker commands, a button can open and close a dialog with HTML alone. The commandfor attribute names the dialog's id, and command says what to do:

<button commandfor="my-dialog" command="show-modal">Open modal</button>

<dialog id="my-dialog" aria-labelledby="my-dialog-title">
  <h2 id="my-dialog-title">Hello!</h2>
  <p>This is a native dialog.</p>
  <button commandfor="my-dialog" command="close">Close</button>
</dialog>
Results

You opened a native <dialog>!

This modal was opened with a button using command="show-modal", with no JavaScript. Press Esc, click outside, or use a button to close it.

Good to know: invoker commands have worked in all major browsers since December 2025. In older browsers the buttons do nothing, so if you need to support them, call showModal() and close() from a click handler instead.

showModal() vs show()

The two ways of opening a dialog behave very differently:

FeatureshowModal()show()
Rest of the pageBecomes inert: can't be clicked, focused or read by screen readersStays fully usable
::backdrop✓ Yes✗ No
Top layer✓ Always on top✗ Normal stacking and z-index apply
Esc closes it✓ Built in✗ Add your own if needed
Typical usesConfirmations, forms, important alertsSide panels, non-blocking settings

Closing and return values

A modal dialog can be closed in several ways: the user presses Esc, your code calls close(), a button uses command="close", or a form with method="dialog" is submitted. Each time, the dialog fires a close event.

The dialog also has a returnValue property, which records how it was closed. It's perfect for confirmation dialogs: give each button a value, put them in a form with method="dialog", and read returnValue in the close event:

<dialog id="confirm" aria-labelledby="confirm-title">
  <form method="dialog">
    <h2 id="confirm-title">Delete this item?</h2>
    <button value="cancel">Cancel</button>
    <button value="confirm">Delete</button>
  </form>
</dialog>

<script>
  const dialog = document.querySelector('#confirm');
  dialog.addEventListener('close', () => {
    console.log(dialog.returnValue);  // "cancel" or "confirm"
    dialog.returnValue = '';          // reset it for next time
  });
</script>
Results
returnValue: (none yet)

Delete this item?

This can't be undone. Watch the value shown next to the button after you choose.

If the dialog is closed with Esc, returnValue isn't changed. That's why the example resets it to an empty string after each close: otherwise a value from a previous time could be read by mistake.

Form integration

When a form inside a dialog uses method="dialog", submitting it closes the dialog and sets returnValue to the value of the submit button that was pressed. Ordinary HTML validation still works, so a required field must be filled in before the dialog will close.

<dialog id="feedback" aria-labelledby="feedback-title">
  <form method="dialog">
    <h2 id="feedback-title">Send feedback</h2>
    <label for="name">Your name</label>
    <input id="name" name="name" required>
    <button value="cancel" formnovalidate>Cancel</button>
    <button value="send">Send</button>
  </form>
</dialog>
  • formnovalidate on the Cancel button lets people close the dialog without filling in the required fields.
  • The data isn't sent anywhere. method="dialog" only closes the dialog, so read the field values in the close event (when returnValue is "send") and send them to your server with fetch().
Results
No feedback sent yet

Send feedback

Styling and animating

Dialogs can be styled like any other element. When opened with showModal(), the browser also adds a ::backdrop pseudo-element covering the page behind it, which you can style too:

dialog {
  margin: auto;                  /* keep it centred, even if a reset removes margins */
  width: min(440px, calc(100% - 32px));
  max-height: calc(100dvh - 32px);
  padding: 24px;
  border: 0;
  border-radius: 14px;
  box-shadow: 0 24px 48px rgb(0 0 0 / 0.25);
}

dialog::backdrop {
  background: rgb(15 23 42 / 0.5);
  backdrop-filter: blur(4px);
}

Keep it centred: browsers centre a modal dialog using margin: auto. If your site uses a CSS reset that sets * { margin: 0; }, that centring is lost, and the dialog sticks to the top-left corner. Setting margin: auto on the dialog, as above, puts it back in the middle of the screen.

Animating in and out

All the demos in this post fade and slide in, then fade out again when closed. Closing animations used to need JavaScript, because a closing dialog disappears instantly. Modern CSS can now animate both directions:

dialog {
  opacity: 1;
  transform: none;
  transition:
    opacity 0.25s ease,
    transform 0.25s ease,
    overlay 0.25s allow-discrete,   /* stay in the top layer while closing */
    display 0.25s allow-discrete;   /* stay displayed while closing */
}

/* Closed state: where it animates to when closing */
dialog:not([open]) {
  opacity: 0;
  transform: translateY(-12px) scale(0.97);
}

/* Where it animates from when opening */
@starting-style {
  dialog[open] {
    opacity: 0;
    transform: translateY(-12px) scale(0.97);
  }
}

@media (prefers-reduced-motion: reduce) {
  dialog {
    transition: none;
  }
}
  • @starting-style sets the styles to animate from when the dialog opens.
  • allow-discrete lets display and overlay (the property that keeps an element in the top layer) wait until the closing animation has finished.
  • Give ::backdrop the same treatment if you'd like it to fade too, as the demos do.

Good to know: @starting-style and allow-discrete work in all major browsers. The overlay property isn't supported everywhere yet; where it's missing, the closing animation can still play, but the dialog may leave the top layer at the start of it. Browsers that support none of this simply open and close the dialog instantly.

Non-modal drawers

Not every panel needs to block the page. A settings panel or a help sidebar can sit beside the content while people keep using the page. Open it with show(), and position it with CSS:

.drawer {
  position: fixed;
  inset: 0 0 0 auto;      /* stick to the right-hand edge */
  width: min(320px, 90vw);
  height: 100dvh;
  max-height: none;
  margin: 0;
  border-radius: 0;
}
Results
The page stays usable while the drawer is open.

Settings

This non-modal dialog was opened with show(). You can still scroll and click the page behind it.

Because a non-modal dialog isn't in the top layer and doesn't make the page inert, the page stays fully usable. That also means Esc doesn't close it automatically, so always include a visible close button, and add a Esc key handler if you'd like one.

Accessibility checklist

The <dialog> element handles a lot of accessibility for you. showModal() makes the rest of the page inert, tells assistive technology the dialog is modal, moves focus into it, and, when it closes, returns focus to the element that was focused before it opened. A few things are still up to you:

  • Give it a name. Add aria-labelledby pointing to the dialog's heading, so screen readers announce what the dialog is about.
  • Include a visible close button. Not everyone knows about Esc, and touch screen users can't press it.
  • Choose where focus starts. By default, focus goes to the first focusable element in the dialog. Add autofocus to a different element, such as the main input, if that's more useful.
  • Consider closing on a backdrop click. The closedby="any" attribute does this natively in Chrome, Edge and Firefox, but not yet in Safari. The demos also use a small click handler as a fallback:
    dialog.addEventListener('click', (event) => {
      // A click directly on the dialog element is on its backdrop,
      // as long as all of the dialog's content sits inside an inner wrapper
      if (event.target === dialog) dialog.close();
    });
  • Test with a keyboard. Open the dialog with Enter, move through it with Tab and Shift+Tab, close it with Esc, and check that focus returns to the button that opened it.

Update: the original version of this post said you need to return focus to the trigger button yourself. Browsers now do this automatically when a modal dialog closes, so the extra code is usually unnecessary, though it's still worth checking.

Browser support

The <dialog> element has worked in all major browsers since March 2022, when Firefox and Safari added support, joining Chrome and Edge. It's safe to use on any website today, with no polyfill needed.

FeatureSupport
<dialog>, showModal(), ::backdropAll major browsers since 2022
Invoker commands (commandfor and command)All major browsers since December 2025
@starting-style and allow-discreteAll major browsers
closedby attributeChrome, Edge and Firefox; not yet Safari

When might you still use a library? If you need features such as drag-to-dismiss gestures on mobile, or complex sequences of dialogs, a thin wrapper library may still be worthwhile. For the vast majority of modals, the native element is the right tool.

Wrapping up

The <dialog> element covers everything a modal needs: the top layer, a backdrop, an inert page, Esc to close, focus handling and form integration. Add invoker commands to open and close it without JavaScript, @starting-style for smooth animations, a heading for its name and a visible close button, and you can retire that old modal library for good.

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee