34

Can I assign one globally defined CSS variable to another locally define variable?

For example, the variable --dark has been globally defined as black.

Then, I want to be able to do:

:root {
    --background-color: --dark
}

.light {
    --background-color: white
}

div {
   background-color: --background-color
}

So that by default, my div will have a black background. And when the class light is added to it, it will have a white background.

I need the 'default' --dark variable here because it is a theme variable.

1 Answer 1

56

You should assign as var(--dark)

:root {
    --dark : black;
    --background-color: var(--dark);
}

.light {
    --background-color: white;
}

div {
  height: 100px;
  width: 100px;
  background-color: var(--background-color);
}
<div class="light"></div>
<div></div>

Sign up to request clarification or add additional context in comments.

1 Comment

And for Ionic, instead of :root, use :host. Thats where I was going wrong!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.