如何实现嵌套div布局中中间层横向滚动、上下两层保持位置固定
问题根源
你当前的实现问题出在中间容器的宽度设置逻辑:你直接给.middle-inner-container设置了1480px的固定宽度,该宽度超过父容器默认宽度后会撑开父容器,导致父容器出现全局横向滚动条;上下绝对定位的元素设置width: 100%会继承被撑开后的父容器宽度,因此会跟着全局滚动一起位移。
调整后完整代码
HTML 结构(无修改)
<div class="outer-container"> <div class="top-inner-container"> xoxoxoxoxoxo </div> <div class="middle-inner-container"> only this must scroll ===> yeah yeah yeah 可以继续加长内容测试滚动效果 </div> <div class="bottom-inner-container"> oxoxoxoxoxox </div> </div>
CSS 样式
.outer-container { height: 470px; position: relative; overflow-x: hidden; /* 新增:禁止父容器横向滚动 */ } .top-inner-container { position: absolute; width: 100%; top: 0px; left: 0px; height: 70px; background: #fff; /* 可选:加背景避免滚动内容透上来 */ } .middle-inner-container { white-space: nowrap; width: 100%; /* 修改:从1480px改为100%,和父容器同宽 */ background-color: grey; overflow-x: scroll; position: absolute; top: 70px; /* 修改:对应顶部容器高度,避免重叠 */ left: 0px; height: 340px; display: flex; } .bottom-inner-container { position: absolute; background-color: #fff; /* 可选:加背景避免滚动内容透上来 */ width: 100%; top: 410px; /* 修改:70+340=410,避免和中间容器重叠 */ left: 0px; }
关键修改说明
- 父容器新增
overflow-x: hidden,主动拦截子元素超宽导致的父容器全局滚动 - 中间容器宽度改为和父容器一致的100%,让
overflow-x: scroll作用于容器内部的超宽内容,滚动条仅出现在中间容器区域 - 修正定位偏移值,避免三个容器出现上下重叠的问题
如果需要中间容器内部的flex子项不被压缩,可以给子项添加flex-shrink: 0属性即可。
内容的提问来源于stack exchange,提问作者Clint William Theron
相关产品推荐
相关产品推荐

