如何将元素定义为仅当元素的剩余高度大于特定大小(我将其称为粘性容器边距)时才表现得像粘性元素?
您可以看到浅蓝色容器有一个粘性红色元素,粘性容器边距显示为深蓝色线。当容器元素离开屏幕时,红色元素保持粘性,直到粘性容器边距到达容器的末尾。
这里是尝试一些解决方案的初始代码。我尝试将蓝线设为容器,但这会弄乱其余内容的初始位置。
section {
height: 300lvh;
}
.content {
background: #eee;
height: 80lvh;
}
.box {
height: 120lvh;
background: #9f9;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.sticky {
position: sticky;
top: 0px;
height: 20lvh;
background: #99f;
}
.end {
color: red;
padding-top: 50px;
}
<section>
<div class="content">Prev content</div>
<div class="box">
<div class="sticky">
Sticky element
</div>
</div>
<div class="content end">
When this is visible, the sticky element should go up
</div>
</section>
如果粘性元素的高度是硬编码的,一种解决方案是对粘性内容使用包装器。
.sticky-wrapper {
height: calc(calc(100% - 100lvh) + var(--sticky-height));
}
section {
height: 300lvh;
}
.content {
background: #eee;
height: 80lvh;
}
.box {
--sticky-height: 20lvh;
height: 120lvh;
background: #9f9;
display: flex;
flex-direction: column;
justify-content: space-between;
position: relative;
}
.sticky {
position: sticky;
top: 0px;
height: var(--sticky-height);
background: #99f;
}
.end {
color: red;
padding-top: 50px;
}
.sticky-wrapper {
height: calc(calc(100% - 100lvh) + var(--sticky-height));
}
<section>
<div class="content">Prev content</div>
<div class="box">
<div class="sticky-wrapper">
<div class="sticky">
Sticky element
</div>
</div>
</div>
<div class="content end">
When this is visible, the sticky element should go up
</div>
</section>