SyntaxStudy
Sign Up
html

How to Create a Modal Dialog

Build an accessible modal popup using the HTML <dialog> element.

The native HTML <dialog> element is the modern way to create modals — no JavaScript framework needed, and it's accessible by default.

Opening and Closing

  • dialog.showModal() — opens as a modal (blocks interaction with background)
  • dialog.show() — opens as a non-modal popup
  • dialog.close() — closes the dialog

Accessibility

The <dialog> element manages focus automatically. Add a aria-labelledby attribute pointing to the modal title for screen readers.

Backdrop

Style the backdrop with the ::backdrop pseudo-element.

Example
<!-- HTML -->
<button id="open-modal">Open Modal</button>

<dialog id="my-modal" aria-labelledby="modal-title">
  <h2 id="modal-title">Modal Title</h2>
  <p>This is the modal content.</p>
  <form method="dialog">
    <button>Close</button>
  </form>
</dialog>

<!-- CSS -->
dialog::backdrop {
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}

dialog {
  border: none;
  border-radius: 12px;
  padding: 2rem;
  max-width: 500px;
  box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}

<!-- JavaScript -->
document.getElementById('open-modal').addEventListener('click', () => {
  document.getElementById('my-modal').showModal();
});