Nested calc operations

跟風遠走 提交于 2019-12-23 06:50:12

问题


Hopefully this is quite simple. I want to use the CSS calc operation to perform two calculations:

I want to set my width to the equivalent of

(100% / 7) - 2

However if I try to perform more than one operation in a CSS calc operation, it fails:

width: calc((100% / 7) - 2);

How can I perform multiple calc operations in one CSS statement?


回答1:


Apparently you have to assign px or % to all numbers that are not being multiplied or divided.

width: calc((100% / 7) - 2px);

Well I feel dumb now. Haha.




回答2:


As David already stated, calc requires px, % or some kind of unit to work. It is possible to use multiple calculations in one statement just like:

width: calc((100% / 7) - 2px);

For anyone else visiting this page looking for answers, it may be worth mentioning that it can be ANY unit. That is, not just px and %, but also em, rem, vh, vw, vmin, vmax, etc. Calc resolves into a value you could use normally, so in the same way you'd never assign width: 100; you should never let the result of calc be unitless.

When dividing or multiplying, it doesn't really make sense to use units on both sides, but it still requires one of the numbers to have a unit so it knows what to assign the result.

/* These are wrong */
width: calc(75 + 25);
width: calc(4 * 20);
width: 100;

/* These are what the browser expects */
width: calc(75px + 25px);
width: calc(20px * 4);
width: 100px;


来源:https://stackoverflow.com/questions/20732457/nested-calc-operations

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