在具有动态高度的其他粘性元素之后堆叠粘性元素

时间:2019-05-29 08:42:12

标签: css sticky

我需要堆叠一些粘性标头元素,如下所示: https://webthemez.com/demo/sticky-multi-header-scroll/index.html

here中的stackover中有针对此问题的解决方案。但是在我的情况下,我的标头具有动态高度。因此,不可能硬编码棒头的顶部位置。我的代码如下:

html

<div class="sticky-header1">
    Header 1 with dynamic height
</div>
<div>
    Header 1 content
</div>

<div class="sticky-header2">
    Header 2 with dynamic height
</div>
<div>
    Header 2 content
</div>

css

.sticky-header1,
.sticky-header2
{
    position: sticky;
}

在这种情况下是否可以设置堆叠式粘性标头?首选纯CSS解决方案。

3 个答案:

答案 0 :(得分:0)

使用纯CSS是不可能的,当已知或恒定高度的元素而不增加元素时,这是可能的(不好)。另一种使用简单javascript的方法,只是计算元素高度并设置CSS位置 top 属性。

---谢谢---

答案 1 :(得分:0)

也许您需要像这样使用javascript:

firstdiv =document.querySelector(".first");
secondiv =document.querySelector(".second");
thirdiv = document.querySelector(".third");
const fheight = firstdiv.offsetHeight;
const sheight = secondiv.offsetHeight;
secondiv.style.top= `${fheight}px`;
thirdiv.style.top= `${fheight+sheight}px`;
body {
  margin:0;
  min-height:200vh;
  border:2px solid;
}
.first {
  height:50px;
  background:red;
  position:sticky;
  top:0;
}

.second {
  height:60px;
  background:blue;
  position:sticky;
}
.third {
  height:80px;
  background:green;
  position:sticky;

}
<div class="first"></div>
<p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>
<div class="second"></div>
<p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>
<div class="third"></div>
<p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>

答案 2 :(得分:0)

我认为您无法仅使用 CSS 来实现这一点。即使您设法做到了,它也会非常脆弱,您需要考虑到有些浏览器不会接受 sticky 位置!我会改用基于 javascript 的解决方案