You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让子div在flex-grow:1的块级父div中占满100%高度?

解决方法

由于.body和.main的样式无法修改,我们可以通过新增嵌套容器并调整其样式的方式,让.should-be-full-height占满父元素.main的高度,以下是两种可行方案:

方案一:Flex布局嵌套

修改后的HTML代码

<div class="body">
  <div class="main">
    <div class="full-height-wrapper">
      <div class="should-be-full-height">
        Content
      </div>
    </div>
  </div>
</div>

新增的CSS样式

.full-height-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.should-be-full-height {
  background-color: grey;
  border: 1px solid black;
  flex-grow: 1;
}

原理:.main作为.body(flex容器)的子元素,flex-grow:1使其占据.body的剩余空间,高度为确定值。新增的.full-height-wrapper通过height:100%继承.main的高度,再利用flex布局的flex-grow:1让内部目标元素自动铺满容器。


方案二:绝对定位

修改后的HTML代码

<div class="body">
  <div class="main">
    <div class="full-height-wrapper">
      <div class="should-be-full-height">
        Content
      </div>
    </div>
  </div>
</div>

新增的CSS样式

.full-height-wrapper {
  position: relative;
  height: 100%;
}

.should-be-full-height {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: grey;
  border: 1px solid black;
}

原理:.full-height-wrapper继承.main的高度并设置为相对定位,目标元素通过绝对定位的top/left/right/bottom:0属性,完全铺满父容器空间,从而占满.main的高度。

内容的提问来源于stack exchange,提问作者sbstnssndn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:18:10