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

  1. Use dialog markup with a form method of dialog for the close button.
  2. Show it with the .showModal() method or the open attribute.
  3. Style the backdrop with ::backdrop and 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

  • ::backdrop only works with .showModal(), not .show().
  • Focus management and aria-modal are still needed for full accessibility.
  • Use dialog { border: none; } to remove default browser styling.