skip navigation

Dialog and Modals

The HTML <dialog> element was created for modals and dialogue boxes.

It’s a block level HTML element that comes with several Javascript methods to open and close it, a CSS pseudo-element ::backdrop, some preconfigured styles such as a border and is automatically centred if a modal.

Modal using the dialog element

Instead of using a div use dialog.

Then use the built in Javascript methods to open and close it. You can use show()or showModal() methods. The latter opened this model.

With showModal() the dialog element will center on the page and have a backdrop added. Then you can use a pseudo-element available in CSS that allows this backdrop to be styled: ::backdrop.

By default it is closed meaning it’s not visible though you can change this by simply adding the open attribute to it.

<dialog open>
    <!-- content -->
</dialog>

However if it’s opened this way it won’t be a modal. For a modal open with the Javascript showModal().

const myModal = document.querySelector('#mymodal');
myModal.showModal();

Javascript

The <dialog> element comes with 3 Javascript methods:

  1. show() opens the element
  2. showModal() opens it as a modal
  3. close() is used to close it again.

Even without a close button the modal can be closed by pressing the esc key on your keyboard. It can also be closed without Javascript using an HTML <form> element (below).

const modal = document.querySelector('#modal');
const openBtn = document.querySelector('.open-btn');
const closeBtn = document.querySelector('.close-btn');

openBtn.addEventListener('click', () => {
    modal.showModal();
})
closeBtn.addEventListener('click', () => {
    modal.close();
})

NB. The show() method has no backdrop and won’t centre the <dialog> element. Because there’s no backdrop the ::backdrop pseudo-element is not available either.

Forms

If you place a <form> element inside your modal and then add an attribute of method="dialog" when you hit submit on your form the modal will close automatically.

So a simple form with a <button> or <input type="submit"> button could be used to close the modal.

<form method="dialog">
    <button>Close</button>
</form>

The CSS

Here’s an example of some CSS you could use.

dialog {
    max-width: 70ch;
    padding: 2rem 4rem;
    background-color: #2E3641;
    color: #fff;
}
dialog::backdrop {
    background: #8005;
    backdrop-filter: blur(5px);
}

Dialog and Modals

From March 2022 the HTML dialog now works in all major browsers. It makes setting up modals easier and comes with built CSS and Javascript methods.

BEWARE: Older browsers still exist out there, particularly on mobile devices where the manufacturer refuses to update the OS, so newer browser's cannot be used.

Kevin Powell video