CSS 变量是否可以用于重新计算其自身的值?

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

在CSS中,我们可以像下面的代码那样将一个变量乘以某个整数吗?

:root {
     --x: 1em;
}

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

不幸的是,对 MDN 文档的快速检查并没有阐明这一点。因此,除非您愿意深入研究规范,否则这里有一个快速测试:

:root {
  --x: 4em;
}

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

从表面上看,不仅计算不起作用——这本身就是不幸的——而且它甚至似乎使 .class2 的自定义 属性 无效。

只是为了确保 formula/approach 使用其他变量创建计算变量通常是有效的:

: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>