CSS Calc中的百分比值 [英] percentage value in css calc

查看:209
本文介绍了CSS Calc中的百分比值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ?
}

根据您要访问的属性(在这种情况下为宽度),可以假定它是宽度还是高度.如果是这样,如果您想基于其他属性进行一些计算,会发生什么?例如,基于对高度的一些计算来设置宽度?是说,将容器的宽度设置为高度的1.5倍?

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?

推荐答案

来自

calc()表达式的计算值是已计算所有成分的表达式.

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

在计算值时间未解析百分比的地方,在calc()表达式中未解析百分比,例如calc(100%-100%+ 1em)解析为calc(1em + 0%),而不是1em.如果某个值(例如height属性)中有用于计算百分比的特殊规则,则只要calc()表达式包含百分比,它们就会适用.

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()一样.

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

因此,使用 width:100% width:calc(100%)完全相同,也与 calc(50%+ 50%).当您添加另一个单位,例如 width:calc(100%-2em)时,就像计算 width:100%一样,然后从其中删除 2em .

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.

基本上,当组合百分比值和非百分比值时, calc()很有用,以便获得准确准确的结果,例如从中删除 10px 通过使用 width:calc(50%-10px)占总宽度的50%.

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?

您不能使用 calc()进行此类操作.CSS通常不允许这样的事情.您可以考虑使用JS,一些 hacks 来保留宽度/高度之间的比率或使用CSS变量并为不同的属性分配相同的值.

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.

有关将 calc()与CSS变量结合使用的相关问题被误用了: Calc()输出意外值

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

这篇关于CSS Calc中的百分比值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆