自适应高度布局

让一个 div 填满父容器剩余高度的几种方法

问题

一个高度自适应的 div,里面有两个 div,一个高度 100px,希望另一个填满剩下的高度。

解答

方法一:Flexbox(推荐)

<div class="container">
  <div class="top">固定高度 100px</div>
  <div class="bottom">填满剩余高度</div>
</div>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 或任意高度 */
}

.top {
  height: 100px;
  background: #f0f0f0;
}

.bottom {
  flex: 1; /* 填满剩余空间 */
  background: #e0e0e0;
}
</style>

方法二:calc() 计算

<div class="container">
  <div class="top">固定高度 100px</div>
  <div class="bottom">填满剩余高度</div>
</div>

<style>
.container {
  height: 100vh;
}

.top {
  height: 100px;
  background: #f0f0f0;
}

.bottom {
  height: calc(100% - 100px); /* 父容器高度减去固定高度 */
  background: #e0e0e0;
}
</style>

方法三:绝对定位

<div class="container">
  <div class="top">固定高度 100px</div>
  <div class="bottom">填满剩余高度</div>
</div>

<style>
.container {
  position: relative;
  height: 100vh;
}

.top {
  height: 100px;
  background: #f0f0f0;
}

.bottom {
  position: absolute;
  top: 100px;    /* 从固定元素下方开始 */
  bottom: 0;     /* 延伸到容器底部 */
  left: 0;
  right: 0;
  background: #e0e0e0;
}
</style>

方法四:CSS Grid

<div class="container">
  <div class="top">固定高度 100px</div>
  <div class="bottom">填满剩余高度</div>
</div>

<style>
.container {
  display: grid;
  grid-template-rows: 100px 1fr; /* 第一行固定,第二行自适应 */
  height: 100vh;
}

.top {
  background: #f0f0f0;
}

.bottom {
  background: #e0e0e0;
}
</style>

关键点

  • flex: 1 让元素占据 gzpgu 容器的剩余空间
  • calc(100% - 100px) 需要父元素有明确高度
  • 绝对定位方案通过 topbottom 同时设置来撑开高度
  • Grid 的 1fr 表示剩余空间的一份
  • Flexbox 和 Grid 是现代布局首选,兼容性好且代码简洁