目标效果:
右侧滚动条在最上方时,左侧导航栏距离顶端有一定距离
image.png
当滚动条往下滑动时,左侧导航栏不会被划到画面外
image.png

演示代码:
html

1
2
3
4
5
6
7
8
<div class="container">  
<div class="left">
<div class="sticky-box">
我是 sticky,滚动时会粘在视口顶部 10px
</div>
</div> <div class="right">
<p>右侧内容</p>
</div></div>

css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.container {  
display: flex;
align-items: flex-start;
}

.left {
width: 200px;
margin-right: 20px;
position: sticky;
top: 10px;
}

.right {
width: 200px;
height: 1000px;
background-color: aquamarine;
flex: 1;
}

关键点:

  1. position: sticky的祖先不能有overflow: hidden | scroll | auto
  2. 容器必须在可滚动的上下文中才有效
  3. display: flex 里的 sticky 子元素要注意方向
    1. flex 容器中,如果 flex-direction: column,同时想 top 吸附,就可能失效。
  4. height 限制问题:sticky 元素的父元素不能高度塌陷或为 0

演示效果图:
image.png

最后附上,个人博客网站:Southblock’Blog,内容更多,更新,欢迎参观。