屬性介紹
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>
效果如下: