如何在子元素滚动时保持元素位置(不使用fixed定位)
实现水平滚动时按钮始终可见(无需fixed定位)
可以通过拆分容器结构来实现,不用fixed定位也能避免复杂的位置计算:
- 将滚动内容单独封装在一个子容器中,让这个容器负责水平滚动
- 把按钮放在外层容器中,使用
position: absolute相对于外层容器定位,而非滚动容器
修改后的代码示例:
<div style="position: relative; height: 100px; width: 400px; background-color: yellow;"> <!-- 按钮相对于外层容器定位,不会随内容滚动 --> <button style="position: absolute; left: 0; top: 0;"> must be visible all time </button> <button style="position: absolute; right: 0; top: 0;"> must be visible all time </button> <!-- 单独的滚动容器,仅内容区域滚动 --> <div style="height: 100%; width: 100%; overflow: auto;"> <div style="height: 100px; width: 600px; background-color: red;"> <br> scroll this </div> </div> </div>
关键说明:
- 外层容器设置
position: relative,作为按钮的定位基准 - 按钮使用
position: absolute固定在左右两侧,不会随滚动内容移动 - 滚动内容容器设置
width: 100%和overflow: auto,仅内部宽内容触发水平滚动,不影响按钮位置
内容的提问来源于stack exchange,提问作者Ondřej Michejda
相关产品推荐
相关产品推荐

