【问题标题】:Why do scrollbars appear when Height, Margins and Padding add up to 100%?为什么 Height、Margins 和 Padding 加起来为 100% 时会出现滚动条?
【发布时间】:2012-03-18 04:31:08
【问题描述】:

我不明白为什么我的第一个 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%。

这是怎么回事?

【问题讨论】:

  • 我没有看到滚动条。你在哪个浏览器中看到这个?

标签: css height margin


【解决方案1】:

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

您的规则是#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 开发工具以类似的方式对其进行分析)

希望这会有所帮助。 异

【讨论】:

  • 感谢您的回答!但是两个元素之间的差距大于 2px(我可能不应该说“101%”(我只是说它比预期的要大)。事实上,我忘记了边距是根据容器宽度计算的:w3.org/TR/CSS2/box.html#margin-properties :“百分比:指包含块的宽度”,而如果边距是“margin-top”或“margin-bottom”,我希望它指的是高度。
【解决方案2】:
#a
{
    height: 100%;
    width: 100%;
    display: block;
    position: relative;
    overflow: auto;
    background-color: indianred;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2018-08-17
    • 2020-07-09
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多