关于父级设置min-height,子级的百分比height失效问题

1,733 阅读2分钟

先说结论:父元素设置min-height时,子元素的百分比高度无效

故事的开始是我想做一个全屏的背景加上一个居中的小div

类似如下效果:

image.png

于是我给body设置了background以及居中三件套:

display:flex;
justify-content: center;
align-items: center;

为了让垂直方向的居中生效(body默认高度为0),又不写死body的高度(后来我想了想其实写死也没关系,不过这是题外话),于是我设置了min-height100vh。然后给子元素设置height50%

<style>
    .parent {
        margin:0;
        background-color: orange;
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
    }
    .child {
        background-color: #fff;
        width: 200px;
        height: 50%;
    }
</style>
<body class="parent">
    <div class="child"></div>
</body>

结果页面中没有子元素,我看了看,子元素高度变成了0。

image.png

排查可能的原因后,我发现只要把bodymin-height改为height问题就解决了。

image.png

min-height存在时有两种情况,一种是父元素的实际高度大于min-height,另一种是父元素的实际高度就是min-height

依据上面的例子,我们可以得出结论:

高度不足min-height的父元素(实际高度等于min-height),其下的子元素百分比高度无效。

然后我们在测试一下第一种情况,给父元素加一个高度超过min-height的子元素。

<style>
    .parent {
        margin:0;
        background-color: orange;
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
    }
    .parent::after {
        content: "";
        display: block;
        width: 0;
        height: 120vh;
    }
    .child {
        background-color: #fff;
        width: 200px;
        height: 50%;
    }
</style>
<body class="parent">
    <div class="child"></div>
</body>

结果如下:

image.png

可以看到右侧出现了滚动条,说明父元素是被撑开了,实际高度大于min-height,但是设置了height: 50%;的子元素高度依旧为0。

终于我们可以得出结论:

父元素设置min-height时,子元素的百分比高度无效