下面是一篇详细、实用的 CSS 教程,总结了 5 种让元素撑满剩余空间的方法,包含示例代码和适用场景,适合新手和进阶开发者参考。


CSS 实现元素撑满剩余空间的五种方法

在网页布局中,我们经常需要某个元素 占据剩余空间,以便自适应屏幕或容器大小。CSS 提供多种方法实现这一目标。


方法 1:Flexbox 弹性布局(最常用)

HTML

<div class="container">
    <div class="header">Header</div>
    <div class="content">Content</div>
</div>

CSS

.container {
    display: flex;
    flex-direction: column;
    height: 100vh; /* 父容器高度 */
}

.header {
    height: 60px;
    background: #4caf50;
}

.content {
    flex: 1; /* 占据剩余空间 */
    background: #f2f2f2;
}

📌 特点

  • 简单高效
  • 推荐现代布局
  • 可横向或纵向撑满

方法 2:Grid 网格布局

HTML

<div class="grid-container">
    <div class="header">Header</div>
    <div class="content">Content</div>
</div>

CSS

.grid-container {
    display: grid;
    grid-template-rows: 60px 1fr; /* 第二行撑满剩余空间 */
    height: 100vh;
}

.header {
    background: #4caf50;
}

.content {
    background: #f2f2f2;
}

📌 特点

  • 灵活布局复杂结构
  • 自动适配剩余空间

方法 3:绝对定位 + 上下边距

HTML

<div class="container">
    <div class="header">Header</div>
    <div class="content">Content</div>
</div>

CSS

.container {
    position: relative;
    height: 100vh;
}

.header {
    height: 60px;
    background: #4caf50;
}

.content {
    position: absolute;
    top: 60px;  /* header 高度 */
    bottom: 0;
    left: 0;
    right: 0;
    background: #f2f2f2;
}

📌 特点

  • 兼容老浏览器
  • 需手动计算偏移量

方法 4:使用 vh 单位

HTML

<div class="content">Content</div>

CSS

.content {
    height: calc(100vh - 60px); /* 减去 header 高度 */
    background: #f2f2f2;
}

📌 特点

  • 直观
  • 父容器固定高度或视口高度时效果最佳
  • 不依赖 Flex 或 Grid

方法 5:使用 Table / Table-cell 模拟布局

HTML

<div class="table">
    <div class="header">Header</div>
    <div class="content">Content</div>
</div>

CSS

.table {
    display: table;
    height: 100vh;
    width: 100%;
}

.header {
    display: table-row;
    height: 60px;
    background: #4caf50;
}

.content {
    display: table-row;
    height: auto;
    background: #f2f2f2;
}

📌 特点

  • 老版 CSS 兼容性好
  • 不推荐复杂布局,但简单页面可用

总结对比

方法特点适用场景
Flexbox简单、高效、现代常规网页布局
Grid强大、灵活复杂布局、多行多列
绝对定位老浏览器兼容需要精确控制位置
vh 单位简单、直观父容器固定高度
Table 模拟老版兼容简单结构或兼容性要求

💡 最佳实践

  • 新项目:优先 Flexbox 或 Grid
  • 老项目兼容:可考虑绝对定位或 Table
  • 注意:Flexbox 与 Grid 内的元素,使用 flex:11fr 最直观