CSS calc() - 带有单位值的乘法和除法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29505279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:09:15  来源:igfitidea点击:

CSS calc() - Multiplication and Division with unit-ed values

csscss-calc

提问by samanime

Is it possible to use calc() to multiply or divide with unit-based values (like 100%, 5px, etc).

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

For example I was hoping to do something like this:

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

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

Hoping it resolved to something like (assuming 100% = 500px):

希望它可以解决类似的问题(假设 100% = 500px):

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

However after some experimenting it looks like I can't have a unit-based value as the denominator for division.

但是,经过一些试验,我似乎无法将基于单位的值作为除法的分母。

I also don't seem to be able to multiple two values together like 5px * 10pxor 5px * 100%.

我似乎也无法将两个值组合在一起,例如5px * 10px5px * 100%

I know it doesn't make sense in 100% of the cases to allow this, but in my use-case, I'd like to know what percentage 120px is of the overall width, which I then feed in to the rest of my calculation.

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

Either that, or if someone could figure out a different way to write it, that would work as well. I've racked my brain and couldn't come up with anything.

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

回答by Andrew Hendrie

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

在 CSS calc() 除法​​中 - 右侧必须是一个<number>因此基于单位的值不能在这样的除法中使用。

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

另请注意,在乘法中,至少有一个参数必须是数字。

The MDNhas great documentation on this.

MDN对这个伟大的文档。

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).

如果您想要更好的计算方式,可以使用预处理器(我喜欢Sass)。该链接会将您带到他们的指南(在该页面上有一个关于运营商的部分)。