Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

Overwrite css variables

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

question from:https://stackoverflow.com/questions/65651420/overwrite-css-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...