我想要一个height:100%的子元素;要应用的容器高度:100%;。当存在文档类型时,这似乎会失败。
如果你使用 min-height:100%;对于父元素,子元素不应用 height:100%;。
如果你使用height:100%;子元素被拉伸(stretch),但会溢出父元素。 如果您随后尝试使用 height:100%;在 parent 身上并保持最小高度:100%;放在 child 身上, child 就不会再伸懒腰了。
这是一个小例子:
<!DOCTYPE html>
<html>
<head>
<title>Oh Well</title>
<style>
html, body {
width: 100%;
height:100%;
background: white;
margin:0;
padding:0;
}
#min-h-100 {
background-color: #eee;
min-height: 100%;
}
#min-h-100 > div{
min-height: 100%;
}
#h-100 {
background-color: #ccc;
height: 100%;
}
#h-100 > div {
height: 100%;
}
</style>
</head>
<body>
<div id="min-h-100">
<div>If this is heigher than the container, the container expands.</div>
<div>The child elements do not get 100% height.</div>
</div>
<div id="h-100">
<div>The child elements get 100% height.</div>
<div>But there will be an overflow.</div>
</div>
<div>THIS SHOULD BE PUSHED DOWN</div>
</body>
</html>
编辑: 最小高度不继承。 @GCryrillus 提出了将 display:table 应用于父级的想法,这至少会拉伸(stretch)父级。 @Volker E. 创建了一个 codepen .
编辑: 如果不想支持IE≤8,可以设置child min-height:100vh;这将使它至少与视口(viewport)一样高。
最佳答案
我觉得这个问题很有趣,尤其是带有 id="h-100"
的案例 #2 暗示了几个 height: 100%
child 在 height: 100%
parent 。
我想出了一个 Codepen including the different options .
为防止在第二种情况下发生溢出,您还可以使用 overflow: hidden
,但这会导致信息丢失。
@GCyrillus 说的对,使用 display: table;
和 display: table-row/table-cell;
符合子 div
s.
#h-100-table {
background-color: #ddd;
display: table;
width: 100%;
height: 100%;
}
#h-100-table > div {
display: table-row;
width: 100%;
}
#h-100-table > div > div { // you don't need to go for extra nesting, but it's clearer.
display: table-cell;
width: 100%;
}
#h-100-table
的孙子不是必需的,更多的是为了可维护性。您也可以只使用 table-row
子项。
关于css - 最小高度 :100% do not apply height:100% 的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22748173/