Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable within an another variable

Tags:

css

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?

like image 644
Lloyd Dominic Avatar asked Apr 07 '26 19:04

Lloyd Dominic


1 Answers

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:

  • Browser support on Can I Use:
    http://caniuse.com/#feat=css-variables
  • Using CSS variables on Mozilla Developer Network:
    https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables
  • Specification on W3C:
    https://www.w3.org/TR/css-variables-1/
like image 83
Sebastian Brosch Avatar answered May 05 '26 11:05

Sebastian Brosch