如何用CSS实现水平滚动时间线的事件标题随滚动保持可见直至容器完全出视口
解决方案
实现结论
可以仅通过CSS实现该需求,核心依赖CSS原生的position: sticky水平粘性定位特性。
修改后的完整代码
<html> <style> .dummy_timeline { width:5000px; top:0px; left:0px; height:20px; background: linear-gradient(90deg, #222 1%, transparent 1%) 1px 0, #fff; background-size: 200px 1px; } .container { overflow: visible; position:absolute; background:#eee; border:1px solid black; width:200px; height:50px; } .title { position: sticky; left: 0; /* 可选:加内边距避免文字贴边 */ padding: 0 8px; line-height: 50px; } </style> <body> <!-- 时间线占位元素,用于撑开滚动宽度 --> <div class='dummy_timeline'></div> <!-- 事件1 --> <div class='container' style='left:120px; top:40px;'> <div class='title'>TITLE1</div> </div> <!-- 事件2 --> <div class='container' style='left:50px; top:140px;'> <div class='title'>TITLE2</div> </div> </body> </html>
效果匹配说明
- 事件容器完全处于视口内时,
sticky定位的标题相对于容器左对齐,保持默认左侧位置 - 页面向左滚动、容器左边缘超出视口左边缘时,标题会自动吸附在视口左边缘,跟随滚动右移保持可见
- 当容器整体完全滑出视口左边缘时,标题跟随容器一起消失,完全符合需求场景
内容的提问来源于stack exchange,提问作者user4550093
相关产品推荐
相关产品推荐

