当您将 min-height 给 parent 并将 percentage height 给 child 时, child 不会获得任何高度。
.p {
min-height: 50vh;
background-color:beige;
}
.c {
height: 50%;
background-color: red;
}
<div class="p">
<div class="c"> hi </div>
</div>
但是如果你给parent明确的高度,即使它小于min-height,child得到一个高度,但是它是相对于min-height而不是提供的高度(当height < min-height时)
.p {
min-height: 50vh;
height: 1px;
background-color:beige;
}
.c {
height: 50%;
background-color: red;
}
<div class="p">
<div class="c"> hi </div>
</div>
- 首先,我想了解这种行为
- 我怎样才能给 child 高度的百分比,只有 parent 的最小高度
这是百分比高度的工作原理 https://developer.mozilla.org/en-US/docs/Web/CSS/height我正在使用此链接,因为它更容易找到,如其他答案中所述,规范链接 https://www.w3.org/TR/CSS22/syndata.html#value-def-percentage
The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto. A percentage height on the root element is relative to the initial containing block.
您必须向下滚动才能找到这个(规范部分)
在您的情况下,由于您没有指定父级的高度,因此您的子级高度计算为自动,这就是您在示例中看到的
这里是如何在不指定父级高度的情况下使用绝对位置来获得百分比高度的工作
.p {
min-height: 50vh;
background-color:beige;
position: relative;
}
.c {
height: 50%;
background-color: red;
position: absolute;
}
<div class="p">
<div class="c"> hi </div>
</div>
注意 - 你 parent 的高度 = min-height 和 height 之间的较大值,这就是你的第二种情况有效的原因
老实说,添加 1px 的高度作为一种解决方法,可以在不定义固定高度(因为最小高度覆盖)的情况下为 child 工作的百分比是一个很好的解决方法。