微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/css/216911.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。