You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在子元素滚动时保持元素位置(不使用fixed定位)

实现水平滚动时按钮始终可见(无需fixed定位)

可以通过拆分容器结构来实现,不用fixed定位也能避免复杂的位置计算:

  1. 将滚动内容单独封装在一个子容器中,让这个容器负责水平滚动
  2. 把按钮放在外层容器中,使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:24:10