如何让粘性元素出现在另一个元素后面?

问题描述 投票:0回答:1

https://jsfiddle.net/30suam6z/1/

.first {
  height: 100vh;
  background-color: red;
  position: relative;
  z-index: 2; /* Increase z-index to ensure it covers .test */
}

.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: -1;
}

.third {
  height: 100vh;
  background-color: blue;
  position: relative;
}
<div class="container">
  <div class="first"></div>
  <div class="second">
   <div class="test">Sticky Element</div>
  </div>
 <div class="third"></div>
</div>

如何让粘性元素 .test 在滚动时出现在 .first 和 .third 元素后面?目前它将粘在 .first 和 .third 元素的边缘。设置 z-index 似乎不起作用。我假设这超出了粘性功能,因为它更多的是元素相互重叠?关于如何实现这种效果有什么想法吗?

编辑:第一个和第三个元素不应该是粘性的,我只是在尝试

EDIT2:更新了代码和小提琴

css sticky
1个回答
0
投票

.test{position: sticky;}
更改为 固定

.first {
  height: 100vh;
  background-color: red;
  position: relative;
  z-index: 2; /* Increase z-index to ensure it covers .test */
}

.second {
  height: 100vh;
  background-color: yellow;
  position: relative;
  z-index: -1;
}

.test {
  width: 95%;
  height: 50px;
  background-color: green;
  margin: 0 auto;
  position: fixed;
  top: 70%;
  z-index: -1;
}

.third {
  height: 100vh;
  background-color: blue;
  position: relative;
}
<div class="container">
  <div class="first"></div>
  <div class="second">
   <div class="test">Sticky Element</div>
  </div>
 <div class="third"></div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.