这是一个简单的html页面。我设置了html,身高100%,但内容很长。
现在我将浏览器缩放到一个小尺寸,滚动条将显示。我打开Chrome Dev工具,body
的计算高度似乎是视口的大小,比如321px。
通常情况下,321px计算高度的主体容器将在页面顶部结束,但实际上主体看起来与整个页面的高度相同,此处为1000px。
这是我的谜题,为什么计算出的高度与实际高度不匹配?
html,body{
width:100%;
height:100%;
background: #ccc;
}
.content {
width: 20px;
height: 1000px;
background: #666;
}

<html>
<head></head>
<body>
<div class="content"> </div>
</body>
</html>
&#13;
答案 0 :(得分:1)
此处您有溢出,因此body
和html
的高度与1000px
不同,因为100%
而等于屏幕高度。< / p>
让您认为body
有1000px
的内容可能是涵盖整个内容的背景,但在这里您面临special behavior of the background called background propagation.
您可以更改html
元素的背景,您将清楚地看到问题:
html,
body {
height: 100%;
background: #ccc;
margin:0;
}
html {
background: red;
border:5px solid green;
}
.content {
width: 20px;
height: 1000px;
background: #666;
}
&#13;
<div class="content"> </div>
&#13;
正如您所注意到的,body
高度不等于内容高度,但仅限于屏幕高度,而您的内容只是溢出了body元素。我还为html
元素添加了一个边框,以显示其高度也仅限于屏幕大小,并更好地突出显示背景传播行为。
答案 1 :(得分:0)
当您将height:100%
设置为元素时,您基本上会告诉它将父母的身高视为自己的身高。
示例:
* {
text-align: right;
}
#parent {
height: 100px;
background: red;
}
#kid {
height: 100%;
width: 200px;
background: lime;
}
#grandkid {
height: 1000px;
width: 100px;
background: orange;
}
&#13;
<div id="parent">
<div id="kid">
<div id="grandkid">
</div>
</div>
</div>
&#13;
如果您希望家长接受孩子的计算身高,请不要为其定义身高。
示例:
#parent {
/* Parent without height takes all of it's children's heights*/
background: red;
}
.kids {
height: 1000px;
width: 40px;
background: lime;
margin-top: 10px;
}
&#13;
<div id="parent">
<div class="kids"></div>
<div class="kids"></div>
</div>
&#13;