CSS Modal Dialog with the Native dialog Element
Modal dialogs without a JavaScript library
The old way was a custom overlay plus JavaScript for open/close, ESC key, click-outside, focus trap, and z-index. The dialog element and showModal() handle most of that, and the closedby attribute adds click-outside.
The old hack vs the modern fix
View demo.overlay {
position: fixed;
inset: 0;
background: rgb(0 0 0 / .5);
}
/* JS: addEventListener click, keydown ESC, focus trap, aria-hidden, body scroll lock, z-index stacking */dialog {
padding: 1rem;
}
dialog::backdrop {
background: rgb(0 0 0 / .5);
}
/* JS: dialog.showModal(); dialog.close(); */Dialog browser support
Live demo
Why the modern way wins
Built-in behavior
Esc closes the dialog and the page behind goes inert. For click-outside, add closedby="any" (Chrome 134, Firefox 141, not in Safari yet).
Accessible by default
The browser manages focus and return focus. Top layer stacking is handled for you.
One element
No overlay div, no z-index wars. Style dialog and ::backdrop and you are done.
- Lines Saved
- 15+ → 6
- No overlay or focus-trap JS
- Old Approach
- Custom overlay + JS
- ESC, click-outside, focus trap, z-index
- Modern Approach
- dialog + showModal()
- ::backdrop, top layer
How it works
The old approach meant a fixed overlay div, JavaScript to open and close it, keydown listeners for Escape, click-outside detection, focus trapping so tab stays inside the modal, and careful z-index management. Easy to get wrong or forget a detail.
The modern approach is a single <dialog> element. Call dialog.showModal() to open it: the browser puts it in the top layer, makes the rest of the page inert and closes it on ESC. Click-outside is not on by default. Add closedby="any" for that (Chrome 134, Firefox 141, not in Safari yet). Style the ::backdrop pseudo-element for the dimmed background. No overlay div, no focus library.