stick定位一如其名:它隨“正常”文檔流而動,直到規定位置,爾后“粘”在那里;或者,當它發現自己可以跟隨“正常”文檔流而脫離sticky位置時,就果斷離開從而加入文檔流。
代碼與效果如下:
<div style="height: 200px; overflow:scroll;"> <p style="background-color:lightgrey; position:sticky; top: 0px;">This is header A</p> <p>This is content A</p> <p>This is content A</p> <p>This is content A</p> <p>This is content A</p> <p style="background-color:lightgrey; position:sticky; top: 0px;">This is header B</p> <p>This is content B</p> <p>This is content B</p> <p>This is content B</p> <p>This is content B</p> <p style="background-color:lightgrey; position:sticky; top: 0px;">This is header C</p> <p>This is content C</p> <p>This is content C</p> <p>This is content C</p> <p>This is content C</p> <p style="background-color:lightgrey; position:sticky; top: 0px;">This is header D</p> <p>This is content D</p> <p>This is content D</p> <p>This is content D</p> <p>This is content D</p> </div>
標題行設置了背景色。如果不設置背景色(背景透明),正常文檔流的文字就會和標題行文字重疊在一起顯示。
sticky定位的元素會遮住滾動而來的“正常”的文檔流;后面的sticky元素會覆蓋前面的sticky元素,就好像一層層的便利貼。
This is header A
This is content A
This is content A
This is content A
This is content A
This is header B
This is content B
This is content B
This is content B
This is content B
This is header C
This is content C
This is content C
This is content C
This is content C
This is header D
This is content D
This is content D
This is content D
This is content D