Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make a modal dialog

Short answer

The dialog tag and one line of JavaScript to open it:

<button onclick="offer.showModal()">Show the offer</button>
 
<dialog id="offer">
  <p>Get 20% off your first order!</p>
  <form method="dialog">
    <button>Close</button>
  </form>
</dialog>

showModal() shows the window above the page, makes the rest of the page unclickable and closes the window on Esc. A form with method="dialog" closes the window when submitted — no JavaScript needed to close it.

Styling

Style the window like a normal block, and the dimmed area behind it with the ::backdrop pseudo-element:

<style>
  .modal { border: none; border-radius: 16px; padding: 24px; max-width: 300px; box-shadow: 0 10px 40px rgb(0 0 0 / 30%); }
  .modal::backdrop { background: rgb(0 0 0 / 50%); backdrop-filter: blur(3px); }
</style>
 
<button onclick="signup.showModal()">Subscribe</button>
<dialog id="signup" class="modal">
  <h3 style="margin-top: 0;">Stay in touch</h3>
  <form method="dialog"><button>No thanks</button></form>
</dialog>

Closing on an outside click

The closedby="any" attribute closes the window on a click on the dimmed background. Not every browser supports it yet; Esc and the button work everywhere.

Common mistake

People show the window with the open attribute or show() and wonder why the background is not dimmed and the page below stays clickable. That is the non-modal version. For a real modal call showModal().

Functions used in this recipe

  • <dialog> — A dialog box; a modal one is opened with `showModal()` and blocks the rest of the page.
  • ::backdrop — The layer right behind a modal `<dialog>` or an element in full-screen mode.
  • <form> — A form: collects data from its fields and sends it to the server.

Thanks for reading!

Donate to the site — we work hard for you.