双向“粘性”位置(“固定”时如何工作)

时间:2019-04-15 12:00:11

标签: css css3 css-position sticky

  • 在第一张图片上,当滚动到达父元素时,粘性元素粘在屏幕底部(如预期)
  • 在第二张图片上,当滚动条使粘性元素居中时,它不会粘贴在任何地方
  • 在第三张图片上,当滚动进一步时,粘性元素会粘在屏幕顶部(如预期)

这是我的问题:

  • 据我了解,当粘性元素到达其在视口中的位置时,粘性位置会切换为“ position:fixed”
  • 在第二张图片上绝对不是这种情况,因为粘性元素不会同时粘在屏幕的顶部或底部
  • 为什么第二张图片上的粘性元素到底在做什么?

.parentSticky {
    width: 50%;
    height: 800px;
    border: solid black 5px;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: auto;
}
.siblingSticky {
    width: 100%;
    height: 100px;
    background-color: orange;
    border: solid 10px red;
    display: inline-block;
    flex: 50 0 1px;
    box-sizing: border-box;
}
.Istick {
    flex-grow: 1;
    border: solid 10px green;
    box-sizing: border-box;
    position: sticky;
    bottom: 10px;
    top: 10px;
}
<!-- break tags illustrate the page's other contents (scrolling demo) -->
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>



<div class="parentSticky">
    <div class="siblingSticky"> Element  </div>
    <div class="siblingSticky Istick" > "Sticky" element </div>
    <div class="siblingSticky"> Element </div>
</div>




<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

fig 1 fig 2 fig 3

1 个答案:

答案 0 :(得分:1)

您忘记了关于粘性的重要部分:

  

粘性定位元素是其计算出的位置值为粘性的元素。将其定位为相对,直到其包含的块超过指定的阈值 ref

因此,在第二张图片中,粘性元素表现为相对元素。

要使用简单的单词,sticky元素仅在由于滚动而隐藏在屏幕上时才表现为粘性,在这种情况下,sticky行为将强制保持可见。如果它已经可见(如第二张图片所示),则不需要任何粘性行为,该元素的行为就像设置了position:relative

top / bottom仅用于定义偏移量。


有关更多详细信息的问题:

Why position:sticky is not working when the element is wrapped inside another one?

Why element with position:sticky doesn't stick to the bottom of parent?

What are `scrolling boxes`?