Many times we need to show a modal to the user, to ask for confirmation, or to show some additional information in a manner which covers the rest of the page user interface. The dialog
element is a great way to do this, and it is supported by all major browsers.
Most recent browsers have implement the fairly recent HTML element called dialog
. It can be used in two cases:
Let’s assume we need to display some overlay on top of an existing interface that needs to cover all elements but not behave as a modal. Basically mimic a higher z-index
value. Try clicking the button below.
Here’s the code for this, the html first:
<dialog id="nmdialog">
<h1>Non-modal dialog</h1>
<p>This is a non-modal dialog</p>
<button onclick="this.parentElement.close()">close</button>
</dialog>
And now the JavaScript:
function showNonModal() {
const dialog = document.getElementById("nmdialog");
dialog.show();
}
This is all that is needed to display such a dialog. We can of course style it with CSS to make it look like or position it as we want.
Similarly, we can display the dialog in a modal manner as well. We only need to call a different function to show it and, if we want, we can style the ::backdrop
.
There are two differences, as I mentioned above:
showModal()
instead of show()
::backdrop
Here’s how we do the styl;ing of the ::backdrop
:
dialog::backdrop {
background-color: color(display-p3 1 0 0 / .33);
}
The ::backdrop
can also be styled as everything else with CSS. One note of warning though: whil;e it supports the recent CSS color syntax it seems to have issues with colors defined in CSS variables, those don’t work for some reason.