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

如何使body div占满屏幕剩余高度且无滚动条(不固定header高度)

问题:让Body Div占满屏幕剩余高度且无滚动条

我的页面结构包含一个header div和一个body div,需求是让body div能够扩展至屏幕的最大可用高度。如果直接给body div设置100vh高度,虽然能占满屏幕,但会忽略header div的高度,导致页面出现滚动条,这是我不希望看到的。

另外我不想给header设置固定高度,也不想使用px单位,避免因字体大小或浏览器差异导致适配问题。

当前使用的代码

CSS代码:

html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
}

.header {
  position: relative;
}

.body {
  position: relative;
  top: 0px;
  bottom: 1rem;
  flex-grow: 1;
}

/* 仅用于可视化 */
.header {
  background: blue;
  color: white;
}

.body {
  background: green;
  color: white;
}

HTML代码:

<body>
  <div class="header">header</div>
  <div class="body">body</div>
</body>

解决方案

只需调整几处CSS设置,就能实现需求:

修正后的CSS代码:

html, body {
  height: 100%;
  margin: 0; /* 消除默认边距,避免出现滚动条 */
}

body {
  display: flex;
  flex-direction: column;
}

.header {
  position: relative;
}

.body {
  flex-grow: 1; /* 仅保留这个属性,自动填充剩余空间 */
}

/* 仅用于可视化 */
.header {
  background: blue;
  color: white;
}

.body {
  background: green;
  color: white;
}

原理说明

  • 给html和body同时设置height: 100%,确保根元素占满整个视口高度,同时添加margin: 0消除浏览器默认的边距,避免意外出现滚动条
  • body使用flex垂直布局后,flex-grow: 1会让.body自动占据header之外的所有剩余空间,完全不需要固定高度或px单位,完美适配不同的header高度和浏览器环境

内容的提问来源于stack exchange,提问作者ほたく

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:02:26