属性介绍
Keeps elements positioned as “fixed” or “relative” depending on how it appears in the viewport. As a result the element is “stuck” when necessary while scrolling.
position属性中最有意思的就是sticky了,设置了sticky的元素,在屏幕范围(viewport)时该元素的位置并不受到定位影响(设置是top、left等属性无效),当该元素的位置将要移出偏移范围时,定位又会变成fixed,根据设置的left、top等属性成固定位置的效果。
可以知道sticky属性有以下几个特点:
- 该元素并不脱离文档流,仍然保留元素原本在文档流中的位置。
- 当元素在容器中被滚动超过指定的偏移值时,元素在容器内固定在指定位置。亦即如果你设置了top: 50px,那么在sticky元素到达距离相对定位的元素顶部50px的位置时固定,不再向上移动。
- 元素固定的相对偏移是相对于离它最近的具有滚动框的祖先元素,如果祖先元素都不可以滚动,那么是相对于viewport来计算元素的偏移量
用法案例
重点是 position: sticky;top:10px
<head>
<style>
.app{
width: 12000px;
height: 2600px;
}
.box{
position: sticky;
top: 10px;
width: 50px;
height: 50px;
background: #ff001c;
}
</style>
</head>
<body>
<div class="app">
<div class="box"></div>
</div>
</body>
效果如下: