49

是否可以使用 calc() 乘以或除以基于单位的值(如 100%、5px 等)。

例如,我希望做这样的事情:

width: calc(100% * (.7 - 120px / 100%));

希望它可以解决(假设 100% = 500px):

width: calc(500px * (.7 - 120px / 500px));
width: calc(500px * (.7 - .24));
width: calc(500px * .46);
width: calc(230px);

然而,经过一些试验,看起来我不能将基于单位的值作为除法的分母。

我似乎也无法像5px * 10pxor一样将两个值组合在一起5px * 100%

我知道在 100% 的情况下允许这样做是没有意义的,但在我的用例中,我想知道 120px 占总宽度的百分比,然后我将其输入到我的其余部分计算。

要么,或者如果有人能想出一种不同的方式来写它,那也行。我绞尽脑汁,什么也想不出来。

4

2 回答 2

58

In CSS calc() division - the right side must be a <number> therefore unit based values cannot be used in division like this.

Also note that in multiplication at least one of the arguments must be a number.

The MDN has great documentation on this.

If you'd like a better way to do calculations you can use a preprocessor (I like Sass). That link will take you to their guides (on that page there's a section about operators).

于 2015-04-08T03:16:59.717 回答
7

对于像我这样犯错误的人,不要忘记你不能直接在 CSS 的函数中使用Sass 变量。calc为此,您必须使用 Sass 的计算方法。

$test: 10px;

.testing{
    width: $test * 2;
}

或者,如果需要calc实施:

$test: 10px;

.testing{
  width: calc(50% + #{$test * 2}); // results in calc(50% - 20px)
}
于 2020-08-31T07:18:56.517 回答