How to create a CSS-only modal overlay
· Category: HTML & CSS
Short answer
The HTML dialog element provides built-in modal behavior. Combined with CSS, you can create overlays, backdrops, and animations without JavaScript.
Steps
- Use
dialogmarkup with a form method ofdialogfor the close button. - Show it with the
.showModal()method or theopenattribute. - Style the backdrop with
::backdropand center the dialog with CSS.
Example
dialog::backdrop {
background: rgba(0, 0, 0, 0.5);
}
dialog[open] {
animation: fadeIn 0.2s ease-out;
}
<dialog id="modal">
<p>Hello from the dialog</p>
<form method="dialog">
<button>Close</button>
</form>
</dialog>
Tips
::backdroponly works with.showModal(), not.show().- Focus management and
aria-modalare still needed for full accessibility. - Use
dialog { border: none; }to remove default browser styling.