1、position:sticky简介
设置了position:sticky
的元素并不会脱离文档流。
- 当元素在区域内,元素不受定位的影响(
top
、left
等设置无效) - 当发生滚动,元素就要移出区域时,定位又会变成
fixed
,根据设置的left
、top
的值进行定位,像是fixed
效果
<div class="sticky">position:sticky</div>
.sticky{width:300px;height: 40px;background-color: lightseagreen;position:sticky;top:0;}
2、必须注意的点
设置了position:sticky
的元素的效果完全受制于父级元素。
此外,还遵循以下条件
- 父级元素不能有任何
overflow:visible
以外的overflow
设置。即使是scroll
或者auto
也不行。 - 父元素的高度不能低于
sticky
元素的高度 - 同一父容器中的sticky元素,如果定位置相等,则会发生重叠,
sticky
元素如果不属于相同父元素,但是他們的父元素正好紧密相连,则会挤开原来的元素,形成依次占位的效果。- 必须制定
top
,left
,bottom
,right
四个中的至少一个,否则其行为与相对定位相同,并且top
和bottom
同时设置时,top
的优先级高;left
和right
同时设置时,left
的优先级高。
3、简单示例
3.1 同一父容器中的sticky元素
<div class="sticky"><div>孵化基地发挥地方发挥地方</div><div>孵化基地发挥地方发挥地方</div><div>孵化基地发挥地方发挥地方</div></div>
.sticky {width:300px;height: 400px; }.sticky div{position: sticky;top:0px;height: 60px;background-color: lightpink;margin-bottom: 20px;}
可以看到,这些stick元素位于同一个父容器内时,当滚动的一定位置时,后面的会覆盖前面的
3.2 sticky元素不属于同一父元素,但父元素正好紧密相连
(为了录制 细节 以及手动操作的 的原因,看着不是很流畅。。。。。实际上很顺滑的。。。)
article h4 { position: sticky; background-color: lightseagreen;color: #fff;padding: 10px;top: 0; }article div{background-color: lightskyblue;}
<article><section><h4>湖人捧奖杯致敬科比鲁UT4923乘客请检测进博会实行核酸检测丰田c_hr青岛已排查密接132人</h4><div>http.createServer(function (request, response) {console.log(request.url,request.pathname,'---------')//var pathname=url.parse(request.url).pathname;var pathname=(request.url).slice(1)||"drag.html";console.log(" 请求 "+pathname+"收到了");</div></section><section><h4>湖人捧奖杯致敬科比鲁UT4923乘客请检测进博会实行核酸检测丰田c_hr青岛已排查密接132人</h4><div>http.createServer(function (request, response) {console.log(request.url,request.pathname,'---------')//var pathname=url.parse(request.url).pathname;var pathname=(request.url).slice(1)||"drag.html";console.log(" 请求 "+pathname+"收到了");</div></section><section><h4>湖人捧奖杯致敬科比鲁UT4923乘客请检测进博会实行核酸检测丰田c_hr青岛已排查密接132人</h4><div>http.createServer(function (request, response) {console.log(request.url,request.pathname,'---------')//var pathname=url.parse(request.url).pathname;var pathname=(request.url).slice(1)||"drag.html";console.log(" 请求 "+pathname+"收到了");</div></section> </article>