一、情况概述

最近在项目布局实现中遇到sticky属性,之前对它的了解不多。这次详细了解它的具体用法。

二、sticky 属性值

MDN 定义

元素根据正常文档流进行定位,然后相对它的最近滚动祖先(nearest scrolling ancestor)和 containing block (最近块级祖先 nearest block-level ancestor),包括 table-related 元素,基于top, right, bottom, 和 left的值进行偏移。偏移值不会影响任何其他元素的位置。

可以把sticky通俗的理解为: relative和fixed布局的混合

三、sticky 使用条件

  • 父元素不能设置overflow:hidden, scroll, auto, 或 overlay属性。
  • 必须指定top、bottom、left、right4个值之一,否则只会处于相对定位
  • 父元素的高度不能低于sticky元素的高度
  • sticky元素仅在其父元素内生效

四、案例

1
2
3
 <div class="box">
<div class="sticky">sticky</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
body {
height: 2000px;
width: 100%;
background-color: red;
}

.box {
height: 400px;
margin-top: 50px;
border: solid deepskyblue;
width: 400px;
background-color: deepskyblue;
}

.sticky {
position: sticky;
top: 20px;
background: yellow;
height: 60px;
line-height: 60px;
}

效果图

效果图