为什么当“高度”、“页边距”和“填充”加起来达到100%时会出现滚动条



我不明白为什么我的第一个div(#a)在这个测试中有一个垂直滚动条:

*, html, body
{
    margin: 0;
    padding: 0;
}
html, body
{
    height: 100%;
    width: 100%;
    position: absolute;
    overflow: hidden;
}
#a
{
    height: 100%;
    width: 100%;
    display: block;
    position: relative;
    overflow: auto;
    background-color: indianred;
}
#b
{
    display: inline-block;
    position: relative;
    height: 90%;
    margin-top: 5%;
    margin-bottom: 5%;
    padding: 0;
    width: 100%;
    background-color: grey;
}
<div id="a">
    <div id="b">TEST</div>
</div>

另请参阅http://dabblet.com/gist/1933615.

在我看来,我的内部div(#b)应该占100%(90%+5%+5%),#a不应该有任何滚动条。但看起来#b占据了101%的份额。

这是怎么回事?

我认为这与像素舍入有关。

你的规则是#b占据#a的90%,顶部有5%的边距,底部有5%的余量。你会认为这相当于100%,对吧?)

运行了两个场景,并在Firebug中检查了Firefox对这些值的处理。

Scenario 1 - #a is 600px tall
#b height = 540px
#b margin-top = 30px
#b margin-bottom = 30px
540 + 30 + 30 = 600px === #a's height
Scenario 2 - #a is 601px tall
#b height = 541px (601 * .9 = 540.9 -> rounded up by browser = 541)
#b margin-top = 31px (601 * .05 = 30.05 -> rounded up = 31)
#b margin-bottom = 31px 
541 + 31 + 31 = 603px > 601px -> #a's height

顺便说一句,如果你在看一个分辨率,所有的比例都给你很好的整数,那么没有滚动条。

如果您想直观地看到这一点并访问Firebug,请检查布局(子)选项卡(当选择HTML选项卡时)。(我相信你可以用Firebug Lite、Chrome开发工具和IE开发工具以类似的方式进行分析)

希望这能有所帮助。iso

#a
{
    height: 100%;
    width: 100%;
    display: block;
    position: relative;
    overflow: auto;
    background-color: indianred;
}

最新更新