主体高度100%显示垂直滚动条 [英] Body height 100% displaying vertical scrollbar

查看:864
本文介绍了主体高度100%显示垂直滚动条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,考虑下面的例子,为什么在#container div上有空白,导致在浏览器中出现垂直滚动条?容器的高度比设置为100%的主体高度小得多。

Out of curiosity, considering the example below, why does having the margin on the #container div cause a vertical scrollbar to appear in the browser? The container is much smaller in height than the body height which is set to 100%.

我为除了#container之外的所有元素设置了填充和边距为0。注意,我有意忽略绝对定位在#container div。在这种情况下,浏览器如何计算body的高度,以及如何影响页边距。

I have set the padding and margins to 0 for all elements except the #container. Note that I have deliberately omitted absolute positioning on the #container div. In this case how is the browser calculating the height of the body and how is the margin affecting it?

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
* { padding:0; margin:0;}
html, body { height:100%; }
#container
{
  padding:10px;
  margin:50px;
  border:1px solid black;
  width: 200px;
  height: 100px;
}
</style>
</head>
<body>
  <div id='container'>
  </div>
</body>
</html>

JSFiddle

推荐答案

如果你绘制 html body 的背景(给出每一个自己的颜色),我们会很快注意到 body 正在向下移动 #container #container 本身并不偏离 body 的顶部。这是边距折叠的副作用,我将详细说明在这里(虽然答案描述了略有不同的设置)。

If you paint the backgrounds of html and body (giving each its own color), you'll quickly notice that body is being shifted down along with #container, and #container itself isn't offset from the top of body at all. This is a side effect of margin collapse, which I cover in detail here (although that answer describes a slightly different setup).

这是导致滚动条出现的行为,因为你已经声明 body 有100%高度 html 。请注意, body 的实际高度不受影响,因为高度计算中不会包含边距。

It's this behavior that's causing the scrollbar to appear, since you've declared body to have 100% the height of html. Note that the actual height of body is unaffected, as margins are never included in height calculations.

这篇关于主体高度100%显示垂直滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆