问题描述
我一直在努力了解这种情况
I have been struggling to understand this scenario
我在CSS中设置了
html, body {
min-height: 100%;
}
这样当页面上没有内容时,html和body 100%的页面高度。如果在体内有内容,这些应该根据内容高度改变它们的高度。
So that when there is no content on the page, the html and body take 100% of the height of page. And if there is content in body, these should change their height according to content height.
但是当我在页面上添加一些内容(足以显示滚动条)时,html和body没有占用文档的100%高度。即如果我的屏幕高度是700px,在任一种情况下 $('body')。height()
将返回700px;
But when I add some content on the page (enough to display scroll bar), html and body are not taking 100% height of the document. i.e. if my screen height is 700px, in either case $('body').height()
would return 700px;
为什么呢?
编辑:
换句话说,我想我的body标签至少是屏幕的100%,但如果添加内容,它应该增长。
In other words, I want my body Tag to be at least 100% of screen but it should grow if content is added.
推荐答案
我第一次误读了这个问题,但第二个想法我会把它解释为:
I've misread the question at first, but on second thought I'd interpret it as:
为什么?
为什么在中,强调我的:
The answer to "Why" is in the relevant spec, emphasis mine:
...
价值:< length> | < percentage> |继承
...
< percentage> ;
指定用于确定使用值的百分比。相对于生成的框的包含块的高度计算百分比。 如果未明确指定包含块的高度(即,它取决于内容高度),并且此元素不是绝对定位的,则百分比值将被视为'0'(对于min-
<percentage>
Specifies a percentage for determining the used value. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').
这是为什么你需要为 min-height
的 html
元素设置高度以在
元素。或者,你可以定位html元素绝对,像这样:
This is why you need to set a height for the html
element for min-height
to work on the body
element. Alternatively you can position the html element absolutely, like this:
html { border: 10px solid black }
body { border: 10px dashed red }
html { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }
/* alternatively: html { min-height: 100%; height: 100%; } */
html { min-height: 100%; }
body { min-height: 100%; }
请参阅或。
See the position: absolute
demo or the height: 100%
demo.
感谢@Alohci纠正我对规范的解释。
Thanks to @Alohci for correcting me on the interpretation of the spec.
这篇关于为什么当min-height:100%时,HTML和BODY不占用文档的所有可用高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!