ShaharAmir
← Back to Blog
HTML1 min read

Stop Building Custom Modals

The HTML dialog element handles modals natively with accessibility built-in

S
Shahar Amir

Stop Building Custom Modals

Still creating modals from scratch with divs, portals, and focus traps?

HTML has a native solution.

The dialog Element

html
12345678
<dialog id="modal">
<h2>Confirm Action</h2>
<p>Are you sure?</p>
<button onclick="modal.close()">Cancel</button>
<button onclick="confirm()">Confirm</button>
</dialog>
<button onclick="modal.showModal()">Open Modal</button>

That's it. Really.

What You Get For Free

  • Backdrop - Automatic overlay (style with ::backdrop)
  • Focus trap - Tab stays inside the modal
  • Escape to close - Built-in keyboard handling
  • Accessibility - Proper ARIA roles included
  • Top layer - Always on top, no z-index wars

Styling the Backdrop

css
1234567891011
dialog::backdrop {
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
}
dialog {
border: none;
border-radius: 12px;
padding: 24px;
max-width: 400px;
}

Two Ways to Open

javascript
12345
// Modal mode (with backdrop, ESC to close)
dialog.showModal();
// Non-modal (no backdrop)
dialog.show();

Getting the Return Value

html
123456
<dialog id="confirm">
<form method="dialog">
<button value="cancel">Cancel</button>
<button value="confirm">Confirm</button>
</form>
</dialog>

javascript
123
confirm.addEventListener("close", () => {
console.log(confirm.returnValue); // "cancel" or "confirm"
});

Browser Support

100% in all modern browsers. Polyfill available for older ones.

Stop reinventing modals. Use

.

#dialog#modal#accessibility

Stay Updated 📬

Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.