<分区>
<分区>
在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%
时才会起作用(在本例中是 body
和 html
元素)。
关于html - 以 % 设置元素高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33680302/