有时给一个元素设置了样式 position: sticky; top: 0 后,希望它吸顶,但是它却没有吸顶。
问题的关键是要搞清楚这个元素吸到了哪个父元素。
MDN 中写到:
Note that a sticky element "sticks" to its nearest ancestor that has a "scrolling mechanism" (created when
overflowishidden,scroll,auto, oroverlay), even if that ancestor isn't the nearest actually scrolling ancestor.
简单翻译一下, position: sticky 会找到最近的设置了 scroll 相关属性的父元素。
比如
<body>
<div class="parent" style="overflow: scroll; height: 2000px">
<div class="child" style="position: sticky; top: 0">sticky</div>
</div>
<body>
当 parent 设置了 overflow 时,child 会吸到 parent 顶部,如果 parent 没有设置 overflow, child 则会吸到 body 顶部。
当 child 吸到 parent 顶部时,如果 parent 很高,那么 child 会随着 parent 滚上去,不会吸到页面顶部。
总结
- 要找到元素吸到哪个父元素的顶部
- 不要随意给元素设置 scroll, 希望元素吸到自己的顶部时再设置 scroll