父元素设置min-height子元素高度设置百分数

4/8/2021 CSS

# 有最小高度的父盒子里面的子元素不能继承高度

现象:对父元素使用 min-height 为 300px,在子元素不脱离文档流的情况下,对子元素设置为 30%,但实际显示的时候,子元素的 height 是 0。

当你让一个元素的高度设定为百分比高度时,是相对于父元素的高度根据百分比来计算高度。当没有给父元素设置高度(height)时 ,浏览器会根据其子元素来确定父元素的高度,所以当无法根据获取父元素的高度,也就无法计算自己高度。

原因:webkit 的 bug,有最小高度的父盒子里面的子元素不能继承高度

原文链接 🔗 (opens new window)

解决

  • 在最外面包裹一层 div,设置为 flex 弹性布局,利用的是弹性盒子默认拉伸高度。
<div class="box-outer">
    <div class="box-inner">
        <div class="content"></div>
    </div>
</div>
1
2
3
4
5
.box-outer {
    display: flex;
}
.box-inner {
    width: 100px;
    min-height: 300px;
    background: #cccccc;
}
.content {
    width: 60px;
    height: 30%;
    background: red;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
  • 给父元素加绝对定位,然后子元素加相对定位,这样子元素的高度就会根据父元素的高度进行计算。
<div class="box-inner parent">
    <div class="content child"></div>
</div>
1
2
3
.box-inner {
    width: 100px;
    min-height: 300px;
    background: #cccccc;
    position: relative;
}
.content {
    width: 60px;
    height: 30%;
    background: red;
    position: absolute;
}
1
2
3
4
5
6
7
8
9
10
11
12

点击我查看 demo 效果 (opens new window)

上次更新: 3/29/2024, 6:09:35 PM