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

如何仅用CSS实现多个position:sticky属性的div不重叠且依次顶出

实现方案

现代浏览器兼容方案(无需修改HTML,纯CSS实现)

你当前需求可以通过CSS滚动驱动动画实现,支持Chrome 115+、Firefox 112+、Safari 15.4及以上版本浏览器,修改后的CSS代码如下:

body{
  padding: 0;
  margin: 0;
}

.Container {
  max-width: 200px;
  margin: 0 auto;
  overflow: hidden scroll;
  height: 200px;
  /* 定义滚动时间线 */
  scroll-timeline: --list-scroll block;
}
.Wrapper {
  padding: 0;
  position: relative;
}

.List {
  margin: 0;
  padding: 0;
  position: relative;
  background: black;
}

.Sticky {
  height: 20px;
  position: sticky;
  top: 0;
  background: rgba(200,70,70,.8);
  /* 绑定顶出动效 */
  animation: sticky-push 1s linear both;
  animation-timeline: --list-scroll;
}
/* 分别设置每个Sticky的动画触发范围,值为对应Sticky出现的滚动位置,可根据实际布局调整 */
.Sticky:nth-of-type(1) {
  animation-range: 70px 90px;
}
.Sticky:nth-of-type(2) {
  animation-range: 240px 260px;
}
.Sticky:nth-of-type(3) {
  animation-range: 410px 430px;
}
@keyframes sticky-push {
  to {
    /* 向上移动自身高度,完全移出视野 */
    transform: translateY(-100%);
  }
}
.Message {
  color: white;
  height: 20px;
  display: block;
  text-align: center;
}

.info {
  background: green;
  color: white;
  height: 50px;
  display: block;
  text-align: center;
}

.spacer {
  background: blue;
  color: white;
  height: 100px;
  display: block;
  text-align: center;
}

低版本浏览器兼容说明

如果需要兼容不支持CSS滚动驱动动画的旧版本浏览器,在你无法修改现有HTML结构添加嵌套父容器的前提下,仅通过CSS无法实现需求,可通过极简JS代码实现:监听滚动容器的scroll事件,计算每个Sticky元素距离容器顶部的距离,当新Sticky滚动到顶部时,给上一个Sticky添加偏移样式即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:24:03