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

举报
福州司马懿 发表于 2021/11/19 02:40:18 2021/11/19
【摘要】 粘性定位 是 相对定位(relative)和 固定定位(fixed)的混合。元素在跨越特定阈值前为相对定位,之后为固定定位。著作权归作者所有。 它主要用在对scroll事件的监听上;简单来说,在滑动过程...

粘性定位 是 相对定位(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>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

补充

粘性定位的固定定位并不一定是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;

  
 
  • 1
  • 2

文章来源: blog.csdn.net,作者:福州-司马懿,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/chy555chy/article/details/85340571

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。