Flexbox 实现头部底部固定、中间自适应布局的关键是:容器设为 column 方向 flex 布局并 min-height: 100vh;header 和 footer 设 flex-shrink: 0 防压缩;main 设 flex: 1 占据剩余空间,并添加 overflow-y: auto 防内容溢出。

用 Flexbox 实现头部底部固定、中间自适应的纵向布局,核心是把容器设为 flex 垂直方向布局,并让中间区域“撑满剩余空间”。
给最外层容器(比如 body 或一个包裹 header、main、footer 的 div)设置:
display: flexflex-direction: columnmin-height: 100vh(确保至少占满视口高度)给三部分分别设置弹性行为:
header, footer:加 flex-shrink: 0(防止被压缩),也可顺手加 flex-grow: 0 和 flex-basis: auto 明确不放大main(或中间内容区):加 flex: 1(等价于 flex-grow: 1; flex-shrink: 1; flex-basis: 0),它会占据所有剩余空间常见问题及处理方式:
立即学习“前端免费学习笔记(深入)”;
main 内容太多导致滚动,建议只让 main 可滚动:main { overflow-y: auto; }
body 默认 margin 干扰,加 body { margin: 0; }
html 或 body 作 flex 容器,需确保它们也继承高度:html, body { height: 100%; }
HTML 结构简洁即可:
<body> <header>顶部</header> <main>这里是自适应的主体内容</main> <footer>底部</footer> </body>
CSS 如下:
html, body {
height: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
header, footer {
flex-shrink: 0;
background: #eee;
padding: 1rem;
}
main {
flex: 1;
overflow-y: auto;
padding: 1rem;
}不复杂但容易忽略细节,关键是理解 flex: 1 在 column 布局里起的是“剩余空间分配器”的作用。
以上就是css初级项目头部底部固定中间自适应怎么办_利用flexbox纵向布局的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号