admin管理员组文章数量:1611904
position:sticky是css定位新增属性;可以说是static(没有定位) 和 固定定位fixed 的结合;它主要用在对 scroll 事件的监听上;简单来说,在滑动过程中,某个元素距离其父元素的距离达到 sticky 粘性定位的要求时(比如top:100px);position:sticky这时的效果相当于fixed定位,固定到适当位置
position 的其他定位
-
absolute:
生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过"left", “top”, “right” 以及 “bottom” 属性进行规定。 -
fixed:
生成固定定位的元素,相对于浏览器窗口进行定位(老IE不支持),元素的位置通过"left", “top”, “right” 以及 “bottom” 属性进行规定。 -
relative:
生成相对定位的元素,相对于其正常位置进行定位,不脱离文档流。 -
static:
默认值,没有定位,元素出现在正常的文档流中(忽略 top, bottom, left, right 或者 z-index 声明)。inherit规定应该从父元素继承 position 属性的值。
sticky定位
sticky
只能在父容器为overflow: scroll
中使用, 而且会根据最近的父容器(overflow:scroll
)产生效果- 必须规定
top
,left
,right
,bottom
中的一种, 否则stikcy
定位相当于relative
- 如果定义了
top
或bottom
属性. 那么父容器height
不能低于top
或者bottom
的值 sticky
属性目前在安卓上适配度不高, 所以 web 在安卓上慎用 sticky 属性
<style>
div.father {
width: 400px;
height: 400px;
overflow: scroll;
background-color: red;
}
div#son-1 {
background-color: green;
width: 300px;
height: 300px;
overflow: scroll;
margin-bottom: 30px;
}
div#son-1 h2 {
width: 100px;
height: 20px;
background-color: pink;
position: sticky;// 寻找在最近父元素为 scroll 属性的
top: 0;
}
div#son-2 {
width: 300px;
height: 300px;
background-color: blue;
position: sticky;
}
</style>
<div class="father">
<div id="son-1">
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>
<h2>hahahaha</h2>``
</div>
<div id="son-2">
<h2>123123123</h2>
</div>
<div id="son-3">
<h2>123123123</h2>
</div>
<div id="son-3">
<h2>123123123</h2>
</div>
</div>
div#son-1 h2
中的position:sticky
会找离的最近的父元素为overflow:scroll
的元素(div#son-1
)进行粘贴效果. 而不是div.father
学习该部分内容视频地址: https://www.bilibili/video/BV1X4411z7ZW?p=13.
版权声明:本文标题:position:sticky 粘性定位 (sticky) 与 固定定位 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1728604705a1165304.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论