2

The question itself is pretty self-explanatory. I have the following code:

:root {
  --brand-color: blueviolet;
  
  --button-background-color: var(--brand-color);
}
body {
  --brand-color: blue;
}

button {
  background-color: var(--button-background-color);
  border: none;
  color: #fff;
  border-radius: 4px;
  padding: 4px 10px;
}
<html>
  <body>
    <button>Button</button>
  </body>
</html>

In the body {...} selector, I have overridden the --brand-color variable. The button is in the body, but the button's background color is still set to the --brand-color defined in the root. I understand that this is the default behavior of CSS variables, but can someone explain to me why this is happening and what is the correct way to override the variable here? Provided, I don't want to override it in the button {...} selector.

darkhorse
  • 8,192
  • 21
  • 72
  • 148

1 Answers1

2

Here's what's happening:

  1. --brand-color is set to blueviolet
  2. --button-background-color is set to the CURRENT VALUE of --brand-color (not a reference to the variable)
  3. --brand-color value is set to blue

Since --button-background-color is never reset, it maintains the original value.

You could use the brand color directly and it would have the correct value.

button {
    background-color: var(--brand-color);
    ...
}
Dan Mullin
  • 4,285
  • 2
  • 18
  • 34