The HTML 'dialog' Element
Table of Contents
- What is the
- Why use
- Exploring Further
- Browser Support
As the name suggests, the
<dialog> element in HTML represents a dialog box such as confirmation, alert, notifications, etc.
Here’s a basic markup for a dialog in HTML:
As you can see, we have a
<dialog> element with
<p> inside of it. But there is no output. The reason behind it is the
<dialog> element comes with some user-agent (or browser default) styling. Let’s have a look at the styles for our dialog:
As we can see, among all the user-agent styles, there is a display: none property. Hence, we cannot see our dialog.
But, how do we see our dialog? Well, that’s simple enough. We use the ‘open’ attribute on our
Looking at the user-agent styles, we can now see that the property display: block is now being used, along with many other default styles such as position, margin, padding, border, etc.
dialog.close(); dialog.show(); dialog.showModal();
close() method simply closes the dialog.
show() method displays the dialog on a webpage. The dialog element can be referenced based on its id or class. A user can interact with what is beneath the dialog when
show() is used. Also, the focus shifts to the dialog from where it was opened.
showModal() method displays the dialog as a modal. When this method is used, it prevents interaction with what is beneath the modal. It also gives us the CSS
::backdrop pseudo-element, which we discuss below. And just like in the
show() method, the focus shifts to the modal when it is opened.
In contrast to the
show() method, the
showModal() method provides us with the following functionalities that we expect a modal to have:
showModal()gives us a
::backdroppseudo-element, which is a box of the size of the viewport itself that appears under the dialog and can easily be customized with CSS.
showModal()prevents interaction with the rest of the webpage.
- You can press the
Esckey to close the modal when it is open.
close() method, you can us a
<form> element inside your dialog. Give your
<form> an attribute of
method="dialog" and you are good to go! Here is an example:
Let’s explore the things explained above with the following CodePen where I have customized a dialog’s backdrop and added animations to a dialog.
As of writing this article, the browser support looks pretty solid for the dialog element on CanIUse.
And that’s about it for the
<dialog> element. As you have seen from the examples in the last CodePen how easy it is to use the dialog element for your modals without coding one up yourself and dealing with all the complexities. Hope you liked this article. Now go have a dialog with HTML. Happy coding! 😀