html - 以 % 设置元素高度

标签 html css layout height width

<分区>

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 元素)。

关于html - 以 % 设置元素高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33680302/

上一篇:css - 更改背景 svg 的条纹 Angular

下一篇:css - 居中水平菜单项

相关文章:

javascript - 使用多个选择选项的搜索功能 - angularjs

javascript - 针对所有 child 而不是仅针对一个 child

javascript - 如何使我的 div 对齐?

html - 如何在 html 元素之间创建一致的间距?

android - 如果我的 Android 项目只有 v21 布局,它会支持旧设备吗?

html - HTML/CSS 中 '' tab'' 的方法是什么?

android - 在 Android 智能手机中禁用输入焦点缩放

jquery - 将 css 添加到 jquery .html() 加载

html - 根据图像缩小以适合 div 和段落?

Android MenuItem 自定义布局