Search code examples
csscss-variables

CSS custom property change on inherited (color) value doesn't work


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>


Solution

  • 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>