Can a CSS variable be used in the recalculation of its own value?

Viewed 226

In CSS, can we we multiply a variable by some integer like the code below ?

:root {
     --x: 1em;
}

.class2 {
     --x: calc(2em * var(--x));
}
1 Answers

A quick check on the MDN docs unfortunately did not shine light on this. So unless you're willing to dive into the spec, here's a quick test:

:root {
  --x: 4em;
}

.class2 {
  --x: calc(0.5 * var(--x));
  font-size: var(--x);
}
<div class="class2">
  Test - doesn't work as intended
</div>

By the looks of it not only does the calculcation not work - which is unfortunate by itself - but it even seems to invalidate the custom property for .class2.

Just to make sure the formula/approach of using other variables to create computed variables in general is valid:

:root {
  --x: 4em;
}

.class2 {
  --y: calc(0.5 * var(--x));
  font-size: var(--y);
}
<div class="class2">
  Test - <strike>doesn't</strike> works as intended
</div>

Related