Modal Dialog
A modal dialog is an overlay that concentrates user attention on a single task. Using the native dialog element with showModal() lets you take advantage of built-in focus trapping and Escape-key behavior.
When to use / not use
Use it when
- When you need users to confirm an important action
- When you want to complete a short form or supporting task without leaving the page
- When you need to present urgent errors or warnings prominently
Don't use it when
- For simple notifications or light feedback → use a toast or banner
- For long, multi-step input flows
- For information that should remain available at all times
Anatomy
- Backdrop — The background overlay styled through
::backdrop - Dialog container — The
dialogelement that holds the interactive content - Title — Indicates the purpose of the dialog and is linked with
aria-labelledby - Body — Holds explanation text, forms, or warnings
- Actions — The set of confirm or cancel controls, which also help define the initial focus target
HTML Structure
Key points
- Use the native
dialogelement and callshowModal()for modal behavior - Use
method="dialog"when you want form submission to close the dialog directly - Provide a proper heading and associate it with
aria-labelledby - Use
autofocusand open/close control logic to define initial focus and focus return clearly
CSS Implementation
Layout and styling
- Use
position: fixedand transforms for stable centering - Use
::backdropto visualize the inactive background layer - Constrain width on mobile with
min()ormax-width - Reset default margins on the dialog to avoid layout drift between browsers
Accessibility
WCAG 2.1.2 No Keyboard Trap
Focus stays inside the dialog, but users also need a reliable way to leave it, such as Escape.
WCAG 2.4.3 Focus Order
Move focus to the right place when the dialog opens, and restore it to the trigger when it closes.
WCAG 4.1.2 Name, Role, Value
aria-labelledby helps screen reader users understand the purpose of the dialog.
Keyboard operation
- Press Escape to close the dialog
- Use Tab and Shift+Tab to cycle through focusable controls inside the dialog
- After closing, focus returns to the trigger button
Live Demo
Confirmation dialog
A minimal confirmation pattern that closes through method="dialog".
Form dialog
A pattern that includes input fields and controls the initial focus target.
Common mistakes
Building it with div instead of dialog
You end up reimplementing focus management and close behavior yourself, which increases both effort and risk.
Poor focus management
Users should keep their interaction context when the dialog opens and when it closes.
Cannot close with Escape
Removing a common dismiss action makes keyboard usage harder.
Unclear backdrop or dismissal rules
If users cannot tell how to close the dialog, they may not be able to complete the interaction.