返回博客

父元素设置 min-height 后,子元素 height: 100% 无效的解决方法

本文探讨了父元素设置 `min-height` 后,子元素设置 `height: 100%` 无效的问题,并提供了六种有效的解决方法,包括使用 `position: relative/absolute`、Flex 布局、Grid 布局以及 `min-height: inherit` 等,并分析了每种方法的优缺点。

Mt.r
|

Mark 一下

父元素设置了 min-height, 子元素设置 height:100% 无效

给子元素添加 min-height inherit,这个方法挺好使的

这个的问题在于,如果父元素的高度比 min-height 高,子元素不会自动变高

参考文章 https://blog.csdn.net/weixin_42335036/article/details/109102609 谷歌浏览器的 bug https://www.jianshu.com/p/164a134401ef

<div class="container">
  <div class="child"></div>
</div>

<style>
  .container {
    min-height: 100px;
    border: 1px solid;
  }
  .child {
    height: 50%;
    background: red;
  }
</style>

解决方法

第一种:父元素设置 position: relative, 子元素设置 position:absolute

<div class="container">
  <div class="child"></div>
</div>

<style>
  .container {
    min-height: 100px;
    border: 1px solid;
    position: relative;
  }
  .child {
    width: 100%;
    height: 50%;
    background: red;
    position: absolute;
  }
</style>

第二种:给父元素加一层 box, 给 box 添加 flex 布局

<div class="box">
  <div class="container">
    <div class="child"></div>
  </div>
</div>

<style>
  .box {
    display: flex;
  }
  .container {
    width: 100%;
    min-height: 100px;
    border: 1px solid;
  }
  .child {
    height: 50%;
    background: red;
  }
</style>

第三种:父元素添加 display: grid;

<div class="container">
  <div class="child"></div>
</div>

<style>
  .container {
    width: 100%;
    display: grid;
    min-height: 100px;
    border: 1px solid;
  }
  .child {
    height: 50%;
    background: red;
  }
</style>

第四种:给子元素添加 min-height inherit,

这个的问题在于,如果父元素的高度比 min-height 高,子元素不会自动变高

第五种:给父元素添加 display: flex; flex-direction: column; 子元素添加 flex: auto;

这个问题在于,没法设置为 50% 的高度。

第六种:display:table