1

I have this example below where .bar is inheriting color: var(--color); from it's parent.

If I then redefine --color to another color in .bar, the custom property doesn't update.

Can someone explain why, and what's needed to be able to change the value of --color in children that inherit that custom property?

:root {
  --color: red;
  --color2: blue;
}

.foo {
  color: var(--color);
}

.bar {
  --color: var(--color2);
}
<div class="foo">
  foo
  <div class="bar">
    bar
  </div>
</div>
Michael Coker
  • 52,626
  • 5
  • 64
  • 64

1 Answers1

1

The property is properly redefined, but until you don't set the color property then the element .bar inherits the color from its parent, and in the scope of the parent that color is red.

:root {
  --color: red;
  --color2: blue;
}

.foo {
  color: var(--color);
}

.bar {
  --color: var(--color2);
  color: var(--color);
}
<div class="foo">
  foo
  <div class="bar">
    bar
  </div>
</div>
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • Thanks! Do you know why this doesn't work? I'm assuming it's by design, but I would expect the variable change to be reflected in the child's color by redefining the variable's value. It's funny, in Safari, if you inspect `.bar`, and then scroll to `.foo` in the dev tools, the var `--color` returns `blue`. – Michael Coker Jan 30 '19 at 18:27
  • Please read again the explanation. You are _redefining_ the variable but you are not _using_ it – Fabrizio Calderan Jan 30 '19 at 19:33
  • @MichaelCoker you should think CSS and not C++ .. you have a cascade, the variable is already evaluated at an upper level and it won't be evaluted again ...read the duplicate and you get more details example and the relevant part of the spec – Temani Afif Jan 30 '19 at 19:53