.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>
(顺便提一下,让我向你保证,我没有意图在生产代码中使用这个;这只是测试中出现的东西.)
解决方法
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的评论:
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是类型检查的一个例外,它在文章的计算值部分中被覆盖.