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

如何实现固定Header、Footer且Main内容可垂直滚动的100vh布局?

解决
标签无法限制尺寸并添加垂直滚动的问题

我看了你的代码,问题出在包含<header>、<main>和<footer>的内层flex容器上——它没有明确的高度约束,导致<main>会被内部的高内容撑开,没法触发滚动效果。咱们来调整一下:

关键修改点

给包裹header、main、footer的div添加h-full类,让它继承外层h-screen的高度,这样flex布局就能正确分配空间,<main>的flex-grow:1就能占据剩余高度,同时overflow-y:auto会在内容超出时触发垂直滚动。

修改后的完整代码

CSS(无需改动,保持原样)

.flex { display: flex; }
.h-screen { height: 100vh; }
.w-96 { width: 24rem; }
.flex-shrink-0 { flex-shrink: 0; }
.flex-grow { flex-grow: 1; }
.flex-col { flex-direction: column; }
.overflow-y-auto { overflow-y: auto; }
.bg-gray-300 { background-color: rgb(209 213 219); }
.bg-red-400 { background-color: rgb(248 113 113); }
.bg-blue-300 { background-color: rgb(147 197 253); }
.bg-red-100 { background-color: rgb(254 226 226); }

HTML(添加h-full类)

<div class="bg-gray-300">
  <div class="flex h-screen w-96 flex-col">
    <!-- 这里添加h-full类,让这个容器占满父级的高度 -->
    <div class="flex flex-grow flex-col h-full">
      <header>Header</header>
      <main class="flex-grow overflow-y-auto">
        <div class="h-screen bg-red-400"></div>
        <div class="h-screen bg-blue-300"></div>
      </main>
      <footer>Footer 2</footer>
    </div>
    <footer class="flex-shrink-0 bg-red-100">Footer 1</footer>
  </div>
</div>

为什么这样修改?

  • h-full让内层flex容器的高度等于父级的h-screen(100vh),这样flex布局的垂直空间是固定的。
  • <header>和<footer>会根据自身内容高度占据空间,<main>通过flex-grow:1填充剩余的垂直空间。
  • 当<main>内部的内容高度超过这个剩余空间时,overflow-y:auto就会自动显示垂直滚动条,而不会撑大整个容器。

这样调整后,你的布局就能实现目标效果:Header和Footer 2固定,Main区域可滚动,底部的Footer 1也保持固定在容器底部。

内容的提问来源于stack exchange,提问作者Daniel Turuș

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:22:41