css – 为什么calc(50%0)有错误?

前端之家收集整理的这篇文章主要介绍了css – 为什么calc(50%0)有错误?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在测试一些新的布局时,我发现自己写了一点
.test1 {width: calc(50% + 0);}

令我惊讶的是,它没有奏效.
在验证我没有打字错误之后,我被迫断定浏览器拒绝了这个错误.那么我以为也许是在我测试的浏览器中的一个缺陷,但另一个行为一样!

那么这个表达式是错的呢?错误在哪里?

p {border:2px solid green}
.test1 {width:calc(50% + 0);}   /* wrong! */
.test2 {width:calc(50%);}       /* OK */
.test3 {width:calc(50% + 0px);} /* also OK */
<p class="test1">test 1</p>
<p class="test2">test 2</p>
<p class="test3">test 3</p>

(顺便提一下,让我向你保证,我没有意图在生产代码中使用这个;这只是测试中出现的东西.)

解决方法

这是由于 Type Checking

At + or -,check that both sides have the same type,or that one side is a <number> and the other is an <integer>. If both sides are
the same type,resolve to that type. If one side is a <number> and the
other is an <integer>,resolve to <number>.

If an operator does not pass the above checks,the expression is
invalid.

您当前的代码有两个值,50%是一个百分比,0是整数/数.它不确认类型检查的规则.

对于Poke的评论

参考Computed Value

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(0% + 1em),not to calc(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.

Note: Thus,the computed value of a calc() expression can be
represented as either a number or a tuple of a dimension and a
percentage.

所以可以说,50%10px是类型检查的一个例外,它在文章的计算值部分中被覆盖.

原文链接:https://www.f2er.com/css/216911.html

猜你在找的CSS相关文章