HTML dialog, occasionally modal

published on August 3, 2023

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.

The dialog element

Most recent browsers have implement the fairly recent HTML element called dialog. It can be used in two cases:

Non-modal dialog

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.

Non-modal dialog

This is a non-modal dialog

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.

Modal dialog

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.

Modal dialog

This is a modal dialog

There are two differences, as I mentioned above:

  1. we need to call showModal() instead of show()
  2. we can style the ::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.