How to Create a CSS Modal with the dialog Element
Build accessible modal dialogs using the HTML dialog element and CSS. No JavaScript library needed.
- Build accessible modal dialogs using the HTML dialog element and CSS.
- The HTML dialog Element.
- Styling Modals with CSS.
- Adding Animations.
- Accessibility Built In.
The HTML dialog Element
The HTML <dialog> element provides native modal functionality: backdrop overlay, focus trapping, Escape key to close, and screen reader semantics β all without a library. Call dialog.showModal() to open as a modal (with backdrop and focus trap) or dialog.show() for a non-modal dialog. Close with dialog.close() or a form with method="dialog". This replaces hundreds of lines of JavaScript that modal libraries implement for focus management, scroll locking, and keyboard handling.
Styling Modals with CSS
Style the dialog with standard CSS. The ::backdrop pseudo-element styles the overlay: dialog::backdrop { background: rgba(0,0,0,0.5); backdrop-filter: blur(4px); }. Style the dialog itself with padding, border-radius, max-width, and box-shadow. Use dialog { max-width: 90vw; width: 500px; border: none; border-radius: 16px; padding: 32px; }. The dialog is automatically centered horizontally and vertically when opened with showModal(). Use the CSS Animation Generator to design entrance/exit transitions.
Adding Animations
Add entrance animations with dialog[open] { animation: fadeIn 0.2s ease; } and dialog::backdrop { animation: fadeIn 0.2s ease; }. For exit animations, use the dialog.close() event to add a closing class, animate out, then remove. Starting with CSS transitions for simpler open/close effects: dialog { opacity: 0; transition: opacity 0.2s; } dialog[open] { opacity: 1; }. Note: the @starting-style rule (Chrome 117+) enables transitions on elements that change display, which is ideal for dialog open transitions.
Accessibility Built In
The dialog element is accessible by default: it traps focus inside the modal (Tab cycles through focusable elements without leaving), returns focus to the trigger element when closed, announces the modal role to screen readers, and closes on Escape key. To enhance: add aria-labelledby pointing to your dialogβs heading, ensure the first focusable element is the most logical action (not the close button), and keep the close button clearly visible and labeled.
Frequently Asked Questions
Do I still need a modal library?
Is dialog supported everywhere?
How do I close a dialog from inside?
Use the CSS Animation Generator β free, no signup required.
β‘ Open CSS Animation Generator