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

父容器横向滚动时,如何用CSS实现子元素(Title)粘性定位?

纯CSS实现横向滚动列表的粘性标题

可以用纯CSS实现这个需求,核心是借助position: sticky属性配合left: 0实现标题的横向粘性固定,同时需要处理背景和层级避免遮挡问题。

调整后的代码示例

HTML结构

<div id="list">
  <div id="list_wrapper">
    <div class="row">
      <span class="title">Title 1</span>
      <span class="content">这里是很长很长的内容,用来触发横向滚动:Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
    </div>
    <div class="row">
      <span class="title">Title 2</span>
      <span class="content">另一段长内容,确保横向滚动生效:Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</span>
    </div>
    <div class="row">
      <span class="title">Title 3</span>
      <span class="content">更多测试内容:Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</span>
    </div>
  </div>
</div>

CSS样式

#list {
  width: 500px;
  height: 300px;
  overflow: auto;
  position: relative;
}

#list_wrapper {
  width: 700px;
}

.row {
  width: 100%;
  height: 50px;
  position: relative;
  background: #ffffff;
  margin-bottom: 4px;
  line-height: 50px; /* 让文字垂直居中 */
}

.title {
  display: inline-block;
  width: 200px;
  position: sticky;
  left: 0;
  background: #ffffff;
  z-index: 1;
  padding: 0 8px; /* 加一点内边距更美观 */
}

.content {
  display: inline-block;
  width: 470px;
}

关键说明

  • position: sticky + left: 0是实现横向粘性的核心:当列表横向滚动时,标题会固定在容器#list的左侧,直到当前行滚出视口
  • 设置背景色(background: #fff)是为了避免滚动时后面的内容穿透标题显示
  • z-index: 1确保标题层级高于内容,不会被内容遮挡
  • 给每行设置背景色可以避免上下行的内容互相干扰

内容的提问来源于stack exchange,提问作者Cilenco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 17:16:06