在 css calc
中指定百分比值时,calc
如何知道我指的是 width
还是 height
?
.container {
width: calc(100% - 2vw); // 100% here is width or height ?
}
根据您正在访问的属性(在本例中为宽度),人们可能会假设它是宽度或高度。如果是这种情况,如果您想根据不同的属性进行一些计算会怎样?例如,根据高度的某些计算来设置宽度?比如说,将容器宽度设置为高度的 1.5 倍?
最佳答案
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.
在 calc()
中使用百分比并没有什么神奇之处,它们的行为就像您没有使用 calc()
一样。
所以使用 width:100%
与 width:calc(100%)
完全相同,后者也与 calc(50% + 50 %)
。当您添加另一个单位,如 width:calc(100% - 2em)
时,就像计算 width:100%
然后从中删除 2em
一样。
基本上,calc()
在结合百分比和非百分比值以获得准确和精确的结果时非常有用,例如 从 中删除
使用 10px
总宽度的 50%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?
你不能用 calc()
做这样的事情。 CSS 通常不允许这样的事情。您可以考虑使用 JS,一些 hacks 来保留 ratio between width/height或者使用 CSS 变量并为不同的属性分配相同的值。
calc()
结合 CSS 变量的使用被误用的相关问题:Calc() outputting unexpected value
关于css - css calc中的百分比值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55658461/