CSS3 粘性定位实现吸顶 position: sticky

粘性定位 是 相对定位(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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值