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

如何让sticky元素滚动时显示在其他元素后方?

实现sticky元素置于其他区块后方的方案

问题核心在于堆叠上下文的限制:你给.second设置了z-index: -1,这会让它创建一个独立的堆叠上下文,内部的.test即使设置z-index,也只能在这个上下文里生效,无法和外部的.first、.third进行层级比较。

调整方案如下:

修改后的CSS代码

.first {
  height: 100vh;
  background-color: red;
  position: relative;
  z-index: 1; /* 确保层级高于sticky元素 */
}

.second {
  height: 100vh;
  background-color: yellow;
  position: relative;
  /* 移除z-index: -1,避免创建独立堆叠上下文 */
}

.test {
  width: 95%;
  height: 50px;
  background-color: green;
  margin: 0 auto;
  position: sticky;
  top: 70%;
  z-index: 0; /* 设为低于.first和.third的层级 */
}

.third {
  height: 100vh;
  background-color: blue;
  position: relative;
  z-index: 1; /* 确保层级高于sticky元素 */
}

对应的HTML结构

<div class="container">
  <div class="first"></div>
  <div class="second">
   <div class="test">Sticky Element</div>
  </div>
 <div class="third"></div>
</div>

调整逻辑说明

  • 移除.second的z-index: -1:取消父级的独立堆叠上下文,让.test的z-index能和外部的.first、.third处于同一层级体系中。
  • 统一层级设置:给.first和.third设置z-index: 1,给.test设置z-index: 0,这样滚动时.test会自然被这两个区块覆盖在后方。
  • 保留position: sticky:确保.test的贴靠行为不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:27:17