以 % 设置元素高度

Set element height in %

this JSFiddle 中,他们展示了如何将页面分成 3 个部分。

但是如果我将 #wrapper 宽度更改为 100% 它会正常工作,那么为什么如果我将 height:400px 更改为 height:100% 它会失败?

#wrapper {
    width: 400px;
    height:400px;
}

如何以百分比“%”覆盖整个页面?

您不应在 CSS 中使用百分比高度。

根据this SO answer

To set a percentage height, its parent element(*) must have an explicit height. This is fairly self-evident, in that if you leave height as auto, the block will take the height of its content... but if the content itself has a height expressed in terms of percentage of the parent you've made yourself a little Catch 22. The browser gives up and just uses the content height.

So the parent of the div must have an explicit height property. Whilst that height can also be a percentage if you want, that just moves the problem up to the next level.

If you want to make the div height a percentage of the viewport height, every ancestor of the div, including and , have to have height: 100%, so there is a chain of explicit percentage heights down to the div.

这意味着父元素必须具有明确的高度(在您的情况下没有)。这是因为 block 元素的高度默认为内容的高度,而 width 默认为 100%。这就是您的 width: 100% 有效的原因。

因此,要获得与 width:100% 类似的功能,只有当它及其所有父元素都设置为 height: 100% 时(在本例中 bodyhtml 个元素)。