如何用Flex实现全屏高度页面且指定区域内容溢出时自动滚动
基于Flex实现固定区域滚动的全屏布局方案
这个需求完全可以通过Flex实现,核心是通过Flex的空间分配能力限制容器高度,再配合溢出属性实现滚动。
参考布局示意图:
核心调整点
- 全局高度重置:给
html、body设置height: 100%; margin: 0;,避免默认边距和高度不足导致全屏失效 - 外层垂直布局:将
body设为垂直Flex容器,顶部header固定高度,下方.container设置flex: 1自动占满剩余全屏高度 - 左侧区域配置:
.content-left作为垂直Flex容器,设置height: 100%占满父容器高度,.content-header、.content-footer保持固定尺寸,需要滚动的红色区域.content-body添加flex: 1; overflow: auto;,即可实现高度自动占满剩余空间、内容溢出自动出滚动条的效果
完整修改后代码
CSS样式
/* 全局高度重置 */ html, body { height: 100%; margin: 0; } body { display: flex; flex-direction: column; } header { /* 可根据实际需求调整header高度 */ height: 60px; background: #eee; } .container { flex: 1; overflow: hidden; } .content { display: flex; height: 100%; } .content-left { display: flex; width: 512px; padding-right: 24px; flex-direction: column; padding-top: 56px; height: 100%; box-sizing: border-box; } .content-header { margin-bottom: 24px; flex-shrink: 0; } .content-header small { display: flex; margin-bottom: 8px; } /* 核心滚动区域配置 */ .content-body { flex: 1; overflow: auto; /* 红色背景可根据需求调整色值 */ background: #f53f3f; flex-shrink: 0; } .content-footer { flex-shrink: 0; margin-top: 24px; } .content-right { display: flex; width: 928px; height: 100%; }
HTML结构
<header>TEST</header> <div class="container"> <section class="content"> <aside class="content-left"> <div class="content-header"> <small>辅助文字</small> <h1> TITLE </h1> </div> <section class="content-body"> <!-- 此处放入大量内容即可测试滚动效果 --> </section> <section class="content-footer"> 底部固定内容 </section> </aside> <div class="content-right"> 右侧内容 </div> </section> </div>
内容的提问来源于stack exchange,提问作者Miomir Dancevic
相关产品推荐
相关产品推荐

