假设我们有以下设置:
null
.container {
background-color: red;
width: 500px;
min-height: 300px;
}
.child {
background-color: blue;
width: 500px;
height: 100%;
}
<div class="container">
<div class="child">
</div>
</div>
null
显然,container
元素呈现的高度设置为300px
,但child
元素没有任何高度,尽管设置为100%
。
当容器
元素的高度设置为偶数1px
时,子
元素将突然以300px
的高度填充整个容器
。
null
.container {
background-color: red;
width: 500px;
min-height: 300px;
height: 1px;
}
.child {
background-color: blue;
width: 500px;
height: 100%;
}
<div class="container">
<div class="child">
</div>
</div>
null
即使没有设置高度,container
元素也清楚地呈现为300px
,那么为什么在子
元素实际应用它的高度:100%
之前需要设置高度呢?
编辑:明确地说,我并不是在寻找一个解决方案,让子元素的高度占据整个父元素,我只是想了解为什么这是这样的行为。
在第一种情况下,您没有定义任何高度,因此很明显,儿童的百分比高度将失败。
根据规范:
指定百分比高度。 百分比是根据生成的框的包含块的高度计算的。 如果包含块的高度没有显式指定(即,它取决于内容高度),并且该元素不是绝对定位的,则值计算为“auto”。
min-height
只是一个边界,元素的高度仍然取决于它的内容。 如果您将有一个超过300px
元素,则该元素将超过300px
null
.container {
background-color: red;
width: 500px;
min-height: 300px;
padding:10px;
}
.child {
background-color: blue;
width: 500px;
height: 400px;
animation:change 2s linear infinite alternate;
}
@keyframes change{
from {
height:100px;
}
}
<div class="container">
<div class="child">
</div>
</div>