Search code examples
javascripthtmlcssdialogbackdrop

How to animate CSS ::backdrop behind HTML <dialog>?


The <dialog> element is now cross-browser compatible (since March 2022).

I tried my hand at it today and familiarised myself with:

  • HTML

    • <dialog>
  • JavaScript

    • .show()
    • .showModal()
    • .close()
  • CSS

    • ::backdrop

Everything seems straightforward but the one thing I've been unable to achieve so far is: fading up the backdrop.

For instance, if I want the final color of the backdrop to be:

  • background-color: rgba(0, 0, 63, 0.8);

but have it transition (or animate) to that background-color from:

  • background-color: rgba(0, 0, 0, 0);

is this even possible?


Here is my (non-working) example:

const myButton = document.querySelector('button');
const myDialog = document.querySelector('dialog');

const requestDialog = () => {
  myDialog.showModal();
  setTimeout(() => myDialog.classList.add('fadeUp'), 400);
}

myButton.addEventListener('click', requestDialog, false);
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 180px;
}

button {
  position: absolute;
  top: 6px;
  left: 6px;
  cursor: pointer;
}

dialog::backdrop {
  background-color: rgba(0, 0, 0, 0);
  transition: backgroundColor 0.6s ease-out;
}

dialog.fadeUp::backdrop {
  background-color: rgba(0, 0, 63, 0.8);
}
<button type="button">Click me to<br />Request Dialog</button>

<dialog>
  <h2>My Dialog</h2>
</dialog>


Solution

  • If you use a box-shadow, it might work and be close enough to what you try to do :

    dialog {
       box-shadow: 0 0 0 100vw rgba(0, 0, 0, 0);
       transition:  2s ease-out;
     }  
    dialog.fadeUp {
       box-shadow: 0 0 0 100vw  rgba(0, 0, 63, 0.8);
       transition:  2s ease-out;
     }