🤯 Create a modal with zero line of CSS 🤯

Jérôme Pott - Sep 24 '18 - - Dev Community

Introduction

HTML 5.2 brought us the dialog element! 🙌

For now, only Chrome implemented it, but other browser vendors will certainly follow if they want to be fully HTML-compliant. (In Firefox, it is already behind a flag.) There's also a polyfill for it.

Let's now examine this relatively new and shiny HTML element. 🔬

Demo

In the codepen below, I created a fully functional modal without writing a single line of CSS. 🤓

So, how does all this work?

Well, it is actually quite simple. We just need to use the dialog element and add the open attribute to display it (by default it is hidden). We can toggle that attribute on by using the showModal method provided on the HTMLDialogElement. We call the close method to toggle it off.

const modal = document.querySelector('#modal')
modal.showModal() // opens the modal
modal.close() // closes the modal

Enter fullscreen mode Exit fullscreen mode

You can notice a few neat things that the dialog element does automatically for us:

  • The dialog is centered in the middle of the screen.
  • The background is dimmed and elements behind the modal can't be interacted with.
  • The dialog has already basic styling (quite ugly, but more on this later).
  • The escape key closes the modal.

And by adding method="dialog" to the form tag:

  • The first interactive element (in the DOM order) is focused.
  • Upon form submission, the dialog is close and the value of the element that triggered the submit event is saved on the returnValue property of the HTMLDialogElement.

In our codepen above, both buttons trigger the closing of the modal. When the modal is closed, it emits a close event. In our demo, modal.returnValue will contain either 'yes' or 'no' (or an empty string if the user presses [escape]).

modal.addEventListener('close', () => {
    console.log(modal.returnValue) // In our case: 'yes', 'no' or ''
})

Enter fullscreen mode Exit fullscreen mode

Customization

The dialog element comes with a default user agent stylesheet, but can be fully customized. You can even change the modal backdrop in this way:

#modal::backdrop {
    background-color: rgba(0, 0, 0, 0.4)
}

Enter fullscreen mode Exit fullscreen mode

An example of customization using Tailwind CSS

Resources

In this post, I only cover some aspects of the dialog element. For detailed information about this topic, I recommend the following links:
https://alligator.io/html/dialog-element/
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog
https://demo.agektmr.com/dialog/

. . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player