我最近在设计网站布局时遇到了一些意想不到的行为.我惊讶地发现,calc()的行为似乎完全改变,取决于它的参数内部是否存在基于百分比的单位.
这是一个最小的复制.
.container { font-size: 30px; display: inline-block; border: solid purple .1em; } .inner { border: solid orange .1em; } .inner.em { width: 3em; } .inner.calc { width: calc(3em + 0%); }
<div class="container"> <div class="inner em">abc</div> </div> <hr> <div class="container"> <div class="inner calc">abc</div> </div>
第二个是令人惊讶的,因为我希望calc(3em 0%)将与3em相同.但是,我测试的每个浏览器都表现出这种行为.此行为发生在任何百分比. 0%不是特别的.这是css规范的这一部分吗?
解决方法
specs for calc明确表示当时没有完全解决:
Where percentages are not resolved at computed value,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.
我会暂时推测10.2:
If the containing block’s width depends on this element’s width,then the resulting layout is undefined in CSS 2.1.
因为这里有一个百分比,所以就像内部块的宽度为150%一样,外部块使用缩放.