粘性定位 是 相對定位(relative)和 固定定位(fixed)的混合。元素在跨越特定閾值前為相對定位,之后為固定定位。著作權歸作者所有。
它主要用在對scroll事件的監聽上;簡單來說,在滑動過程中,某個元素距離其父元素的距離達到sticky粘性定位的要求時(比如top:100px);position:sticky這時的效果相當於fixed定位,固定到適當位置。
注意:起作用的,除了 top 值,還有right、left、bottom。
常見的吸頂、吸底(移動端網站的頭部返回欄,底部切換欄之類)的效果,都可以用這個屬性實現。
舉個例子:
<!DOCTYPE html> <html> <meta charset="utf8"> <head> <style> section:first-child { height: 200px; background-color: lightgray; } section:nth-child(2) { height: 100px; background-color: orange; position: sticky; position: -webkit-sticky; top: 50px; } section:nth-child(3) { height: 300px; background-color: lightgray; } section:nth-child(4) { height: 100px; background-color: orange; position: sticky; position: -webkit-sticky; top: 150px; } section:last-child { height: 500px; background-color: darkgray; } </style> </head> <body> <section>SECTION-1</section> <section>SECTION-2</section> <section>SECTION-3</section> <section>SECTION-4</section> <section>SECTION-5</section> </body> </html>
粘性定位的固定定位並不一定是position:fixed,只有目標元素的任意父元素都沒有設置position:relative | absolute | fixed | sticky的情況下,才與position: fixed表現一樣。而當其任一父元素設置了position:relative | absolute | fixed | sticky時,目標元素是相對於父元素的固定。
在 https://caniuse.com/ 這個網站能查看 API 的支持情況:
webkit 內核的瀏覽器需要在屬性值加前綴“-webkit”才能使用。
position: sticky;
position: -webkit-sticky;