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

眉间皱痕 提交于 2019-12-21 06:47:29

问题


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

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

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 * 10px or 5px * 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.

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.


回答1:


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



来源:https://stackoverflow.com/questions/29505279/css-calc-multiplication-and-division-with-unit-ed-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!