percentage value in css calc

随声附和 提交于 2020-07-21 03:47:09

问题


While specifying a percentage value in css calc, how does calc know whether I am referring to width or height?

.container {
    width: calc(100% - 2vw); // 100% here is width or height ?
}

One may assume that it is either width or height depending on the property you are accessing, (width in this case). If that were the case, what happens if you would like to do some calculation based on a different property? For instance, set the width based on some calculation of height? Say, set the container width to be 1.5 times height?


回答1:


From the specification

The computed value of a calc() expression is the expression with all components computed.

Where percentages are not resolved at computed-value time, they are not resolved in calc() expressions, e.g. calc(100% - 100% + 1em) resolves to calc(1em + 0%), not to 1em. If there are special rules for computing percentages in a value (e.g. the height property), they apply whenever a calc() expression contains percentages.

There is no magic when using percentage inside calc() they will simply behave as if you aren't using calc().

So using width:100% is exactly the same as width:calc(100%) which is also the same as calc(50% + 50%). when you add another unit like width:calc(100% - 2em) it's like calculating width:100% then you remove 2em from it.

Basically, calc() is useful when combining percentage and non-percentage value in order to have accurate and precise result like removing 10px from 50% of the total width by using width:calc(50% - 10px).


what happens if you would like to do some calculation based on a different property? For instance, set the width based on some calculation of height?

You cannot do such thing with calc(). CSS in general doesn't allow such thing. You can either consider JS, some hacks to preserve ratio between width/height or use CSS variable and assign the same value for different properties.


Related question where the use of calc() combined with CSS variable is missused: Calc() outputting unexpected value



来源:https://stackoverflow.com/questions/55658461/percentage-value-in-css-calc

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