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

如何让带头部和底部的可滚动内容区适配视口高度

问题描述

需要实现包含头部(header)、可滚动内容区(body)和底部(footer)的页面布局,头部与底部高度由内部组件决定,要求内容区自动占据视口剩余空间,使整体页面适配视口高度。

原始代码示例

HTML

<div class="container">
  <div class="header">Header</div>
  <div class="body" id="body"></div>
  <div class="footer">Footer</div>
</div>

CSS

.row {
  background-color: red;
  padding: 10px;
  margin: 0 0 5px 0;
}

.container {
  height: 100vh;
}

.header {
  height: 100px; /* 示例固定高度,实际由内部组件决定 */
  background-color: yellow;
}

.body {
  overflow-y: scroll;
  /* 需要设置高度以占据视口剩余空间 */
}

.footer {
  height: 100px; /* 示例固定高度,实际由内部组件决定 */
  background-color: orange;
}

JavaScript

const body = document.getElementById('body');

const createFakeData = (id) => {
  const row = document.createElement('div')
  row.innerHTML = "Row" + id;
  row.classList.add('row')
  body.appendChild(row);
}

for (let i = 0; i < 100; i++) {
  createFakeData(i);
}

解决方案

方案一:Flexbox布局(推荐)

利用Flexbox的弹性特性,让内容区自动填充剩余空间,完美适配头部和底部的动态高度。

修改后的CSS代码:

.row {
  background-color: red;
  padding: 10px;
  margin: 0 0 5px 0;
}

/* 清除页面默认边距,避免视口溢出 */
body {
  margin: 0;
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: column; /* 垂直排列子元素 */
}

.header {
  /* 移除固定height,高度由内部内容决定 */
  background-color: yellow;
  padding: 1rem; /* 示例内边距,可按需调整 */
}

.body {
  overflow-y: auto; /* 内容超出时显示垂直滚动条 */
  flex: 1; /* 占据容器剩余的所有空间 */
}

.footer {
  /* 移除固定height,高度由内部内容决定 */
  background-color: orange;
  padding: 1rem; /* 示例内边距,可按需调整 */
}

核心逻辑:

  • 容器设为flex-direction: column,让子元素垂直分布
  • flex: 1让内容区在头部和底部布局完成后,自动填充剩余空间
  • overflow-y: auto保证内容过多时可以滚动,无溢出时隐藏滚动条

方案二:Grid布局

Grid布局通过行模板定义,同样可以实现自适应剩余空间的效果。

修改后的CSS代码:

.row {
  background-color: red;
  padding: 10px;
  margin: 0 0 5px 0;
}

/* 清除页面默认边距 */
body {
  margin: 0;
}

.container {
  height: 100vh;
  display: grid;
  /* 头部、底部高度由内容决定,内容区占剩余空间 */
  grid-template-rows: auto 1fr auto;
}

.header {
  background-color: yellow;
  padding: 1rem;
}

.body {
  overflow-y: auto;
}

.footer {
  background-color: orange;
  padding: 1rem;
}

核心逻辑:

  • grid-template-rows: auto 1fr auto:auto表示行高随内容变化,1fr表示占据剩余的全部空间
  • 内容区同样通过overflow-y: auto实现滚动

注意事项

  • 必须清除body的默认margin,否则容器的100vh会加上默认边距,导致页面出现垂直滚动条
  • 两种方案都支持头部/底部高度动态变化(比如加载新内容后高度改变),无需手动调整样式
  • 避免使用calc()计算内容区高度,因为头部/底部高度不确定时,该方法无法自适应内容变化

内容的提问来源于stack exchange,提问作者Mush-A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:17:49