18

I am trying to set a CSS variable with a number then I want to use it in my CSS as a percentage, while in other places I will need to use it as a plain number for some calc() operations.

Example

--mywidth:10;

div{width:var(--mywidth) + %;}  --- should be ---> width:10%

is it possible?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Ziv Feldman
  • 321
  • 2
  • 13

1 Answers1

27

Use calc() and do a simple multiplication with any unit:

div{width:calc(var(--mywidth) * 1%);}

example:

:root {
  --a:50;
}

.box {
  width:calc(var(--a) * 1%);
  border:calc(var(--a) * 0.5px) solid red;
  background:linear-gradient(calc(var(--a) * 0.8deg),blue 50% ,green 0);
  padding:20px;
  
  box-sizing:border-box;
}
<div class="box"></div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415