3

Is it possible to let a property variable have a value of an another variable?

Like this:

:root {
    --theme-primary: --color-red;
    --color-red: #F44336;
}

... or:

:root {
    --theme-primary: var(--color-red);
    --color-red: #F44336;
}

If possible, what is the code, without using JS as possible?

1
  • 1
    Since CSS Variables are kind of new I'll just add a link for those who haven't heard of it. Commented May 11, 2017 at 6:27

1 Answer 1

4

It's possible. In the following example the variable --theme-primary gets the value of --color-yellow. If it is not possible (the variable --color-yellow isn't defined or not valid) --theme-primary would be black (#000).

:root {
  --theme-primary: var(--color-yellow, #000);
  --color-yellow: yellow;
  --color-blue: blue;
}
:root {
  --theme-secondary: var(--color-blue);
}
div {
  background: var(--theme-primary, green);
  border:5px dashed var(--theme-secondary, white);
  height:100px;
  width:100px;
}
<div>Hello World</div>

You can also use a variable as fallback (second parameter of val). So you can do something like var(--theme-primary, var(--theme-secondary, white));

Additional links:

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

5 Comments

My primary browser is Firefox, running the latest version, and I'm sure that all major browsers support that.
Hmmm ... I'm a little curious about what that "second value" in the var() was. Is it the fallback value if something error goes with the variable?
@LloydDominic - that's right! If the first parameter fails, the second parameter take effect. And you see in the example above no fallback is used, so the first parameter is successfully used.
But, can it take for multiple parameters for multiple fallbacks, or just two parameters?
You can do something like this: var(--theme-primary, var(--theme-secondary, white));

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.