首页 >web前端 >css教程 >我们可以在纯 CSS 中将多个粘性元素堆叠在一起吗?

我们可以在纯 CSS 中将多个粘性元素堆叠在一起吗?

DDD
DDD原创
2024-11-01 02:00:02948浏览

Can we Stack Multiple Sticky Elements on Top of Each Other in Pure CSS?

在纯 CSS 中实现多个堆叠的绝对定位粘性元素

问题:

是否可以在纯 CSS 中将多个粘性元素堆叠在彼此之上?

示例:

https://webthemez.com/demo/sticky-multi-header-scroll/index.html

我更喜欢使用纯 CSS,而不是 JavaScript 实现。我已经尝试过多个粘性元素,但我无法阻止它们挤出其他粘性元素。我尝试将它们放在相同的堆叠上下文中:

#sticky .sticky-1,
#sticky .sticky-2
{
  position: sticky;
}
#sticky .sticky-1
{
  top: 1em;
  z-index: 1;
}
#sticky .sticky-2
{
  top: 2em;
  z-index: 1;
}

但它无法正常工作,正如你可以在下面的 .html 片段中看到的。任何见解都将不胜感激!

<code class="html"><div id="container">
  <article id="sticky">
    <header>
    </header>
    <main>
      <h1 class="sticky-1">Sticky heading</h1 >
      <p>here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. Some copy goes here. </p>
    </main>
    <section>
      <h2 class="sticky-2">Both headings should stick at the same time.</h2 ></code>

以上是我们可以在纯 CSS 中将多个粘性元素堆叠在一起吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn