Overwrite css variables

Viewed 234

I have a component that declares and use a css variable "--test: red"

But I want to re-declare this variable with a new color outside this component.

https://stackblitz.com/edit/js-va9k9q?file=style.css

Is this rule right?

:root *{
  --test: green;
}

Why * is required? If I remove this, it doesn't work

:root *{
  --test: green;
}
#app {
  --test: red;
}
#app h1{
  background-color: var(--test);
}

Html

<html>
<body>
    <div id="app"><h1>Example</h1></div>
</body>
</html>

The final result must have a green background-color

2 Answers

Use a second variable in case you want to only consider :root

:root {
  --new: green;
}

#app {
  --test: red;
}

#app h1 {
  background-color: var(--new, var(--test)); /* will fallback to "test" if "new" is not defined */
}
<div id="app">
  <h1>Example</h1>
</div>

Or you keep using the code you show which is correct since you will target all the elements (with *) to set the variable --test that will get used instead of the one inherited from #app

enter image description here

This is about ordering and priority of css selectors

if you do like this:

:root {
  --test: red;
}

.
.
.

:root {
  --test: green;
}

the second selector have more priority

but if you do:

:root #app{
  --test: green;
}

.
.
.

:root {
  --test: red;
}

the first selector will apply for #app. if another block is defined outside of #app, it would get red color.

:root * {} works because it have more priority.

read more about priority in this link

Related