Flexbox布局:子元素占剩余空间不超限,内容溢出可滚动实现问题
问题根因
你遇到的问题是Flex布局的默认规则导致的:沿主轴(此处是垂直方向column)排列的Flex子项默认min-height值为auto,会优先适配内容高度,即便设置了flex:1也会被内容撑开,导致overflow: auto不生效。另外body标签默认自带的外边距也会导致100vh高度超出视口,触发页面滚动条。
解决方案
做两处修改即可:
- 重置body默认外边距,避免视口高度溢出
- 给需要滚动的第二个Flex子项添加
min-height: 0,覆盖默认规则,允许子项高度小于内容高度
修复后完整代码
<!-- 先重置body默认样式 --> <body style="margin: 0;"> <div style="max-height: 100vh; height: 100vh"> <div style="height: 100%; display: flex; flex-direction: column"> <div style="flex: 0 1 auto"> This is some fixed heighted content </div> <!-- 新增min-height: 0 --> <div style="flex: 1 1 0%; overflow: auto; min-height: 0"> A lot of text content here that overflows the remaining space. So this div should take up the remaining available space (100vh - space of div above) and the inner content should become scrollable But it ends up expanding the div to the text content and thus the whole screen becomes scrollable instead of just the div </div> </div> </div> </body>
效果说明
修改后外层容器高度固定为100vh,第一个div高度由内容本身决定,第二个div自动填充剩余视口空间,内部内容超出时仅该区域出现滚动条,不会撑高整个页面触发全局滚动。
内容的提问来源于stack exchange,提问作者Ujjwal Chadha
相关产品推荐
相关产品推荐

