26

I'm trying to change the background color of a dialog element's backdrop using a custom CSS property but it won't take. Is this a bug in Chrome or is there a reason for this?

document.querySelector('dialog').showModal();
:root {
  --color-backdrop: red;
}

dialog::backdrop {
  background: var(--color-backdrop);
}
<dialog>
  <p>This is a dialog. My backdrop should be red.</p>
</dialog>
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
powerbuoy
  • 12,460
  • 7
  • 48
  • 78

1 Answers1

23

The spec states the following about ::backdrop pseudo-element:

It does not inherit from any element and is not inherited from. No restrictions are made on what properties apply to this pseudo-element either.

And to quote Xindorn Quan, a member of WHATWG, regarding CSS Custom Properties:

CSS variables are propagated via inheritance into descendants, so if a pseudo-element doesn't inherit from anything, CSS variables which are not defined for the pseudo-element directly would have no effect on the pseudo-element.

Finally, this is one solution for this kind of problem:

document.querySelector('dialog').showModal();
::backdrop {
  --color-backdrop: red;
}

dialog::backdrop {
  background: var(--color-backdrop);
}
<dialog><p>This is a dialog. My backdrop should be red.</p></dialog>

It seems to be useful for multiple modals with ::backdrop, as a way of organizing their "root", so to speak.

Rick Stanley
  • 732
  • 2
  • 9
  • 23
  • Oh I see, so it won't inherit custom properties set on `:root` at all... that's a little annoying as we keep all our "config" in one file and they're all set on `:root`. Having to set one specific config variable on `::backdrop` (as well as `:root` as it's used by other things too) will be a little annoying. – powerbuoy Aug 12 '20 at 14:33
  • 11
    :root, ::backdrop { --color-backdrop: red; } Then it's available to both – Phil Aug 15 '20 at 04:20