position: sticky -粘性定位(是css新增的一个position属性)
使用注意事项:
-
父元素不能有 overflow 属性
-
left、top、right、bottom必须要设置一个
-
仅在父元素内生效,父元素的高度必须大于sticky元素设置的高度
简单理解就是,当你页面滚动的距离小于你设置的 left、top、right、bottom的值时
position: sticky 就相当于 position:relative
当你页面滚动的距离小于你设置的 left、top、right、bottom的值时
position: sticky 就相当于 position:fixed
代码展示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
/*粘性定位,当用户滑动的距离超过top设置的值时,就相当于position:fixed定位
当用户滑动的距离没超过top设置的值时,就相当于position:relative定位*/
.csstricky{
position: sticky;
width: 30px;
height: 30px;
background: aqua;
top: 50px;
}
#fs{
height: 2000px;
width: 100%;
}
#ad{
height: 300px;
width: 100%;
background:black;
}
</style>
</head>
<body>
<div id="fs">
<div id="ad"></div>
<div class="csstricky"></div>
</div>
</body>
</html>
当<div class="csstricky"></div>这个div距离顶部小于我们所设置的 50px 的时候,
position: sticky 就相当于 position:fixed ,div就会被固定在top:50px 的位置处
好啦,今天的学习就到这啦,文章有什么问题可以在评论区指正哦~❤️
本文介绍了CSS的position:sticky特性,它使得元素在页面滚动时在特定位置切换相对和固定的定位。当页面滚动距离小于设置的top值时,元素表现为relative定位;超过该值则变为fixed定位。示例代码展示了如何实现这一效果。了解这一特性有助于提升网页布局的交互体验。

1408

被折叠的 条评论
为什么被折叠?



