css - css calc中的百分比值

标签 css css-calc

在 css calc 中指定百分比值时,calc 如何知道我指的是 width 还是 height?

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

根据您正在访问的属性(在本例中为宽度),人们可能会假设它是宽度或高度。如果是这种情况,如果您想根据不同的属性进行一些计算会怎样?例如,根据高度的某些计算来设置宽度?比如说,将容器宽度设置为高度的 1.5 倍?

最佳答案

来自 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.

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/

相关文章:

css - 如何将 css calc() 的值分配给 css 变量,而不是让它延迟计算直到使用 css 变量

css - 在 ionic4 的网格单元格中用一个字母居中圆圈

jquery - CSS 缩放属性不起作用 (Jquery)

jquery - css - 在列表中对齐居中图像

css - 阻止 div 宽度将其推错位置

CSS calc() 四舍五入

html - "width: calc(100%/3);"工作不正常

javascript - 如何使 div 在点击关闭时关闭并隐藏?

css - 在 FireFox 29.0.1 中不工作 css calc()