1

I am trying to overwrite color value here that's not applying in Chrome at least. Wondering if this is a bug or just a limitation of CSS vars.

The --contrast-color I am overwriting isn't taking effect (#fff). However, obviously, normally overwriting --title-color works fine if I define it again in .dark as --title-color: var(--contrast-color);

:root {
  --contrast-color: red;
  --title-color: var(--contrast-color);
}


.dark {
  --contrast-color: #fff;
  background: #000;
}

.title {
  color: var(--title-color);
}
<div>
  <h1 class="title">
    Heading (should be red)
  </h1>
</div>

<div class="dark">
  <h1 class="title">
    Heading (should be #fff)
  </h1>
</div>
Sam
  • 41
  • 2

1 Answers1

1

the variable --title-color: var(--contrast-color); is defined for the :root element while you update --contrast-color on .dark element.

If you want to have that reference automatically updated, without the need of redeclaring --title-color, both the variables --contrast-color should be declared for the same element (e.g. on the div as in the example below, but I recommend to apply the theme class to a common container, like :root)

An update on a variable would eventually re-evaluate a reference on its descendants, not on the ancestors: in fact, if the update of the variable also affected the ancestors overriding the same property, then it would change instantly, on cascade, the other title too.

So as a result both the titles would be white coloured.

div {
  --contrast-color: red;
  --title-color: var(--contrast-color);
}


div.dark {
  --contrast-color: #fff;
  background: #000;
}

.title {
  color: var(--title-color);
}
  
<div>
  <h1 class="title">
    Heading (should be red)
  </h1>
</div>

<div class="dark">
  <h1 class="title">
    Heading (should be #fff)
  </h1>
</div>
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • Thanks. I am aware of that but I am more curious about the why. In other languages, usually cyclical references are supported. So I am curious if this is a bug or a limitation. – Sam Mar 03 '20 at 11:37
  • 1
    because a change of --contrast-color would change the reference of --title-color defined on a descendants element, not on ancestors. – Fabrizio Calderan Mar 03 '20 at 11:41