CSS——粘性定位(sticky)
sticky 英文字面意思是粘,粘贴,所以可以把它称之为粘性定位。position: sticky;基于用户的滚动位置来定位。粘性定位的元素是依赖于用户的滚动,在position:relative与position:fixed定位之间切换。它的行为就像position:relative;而当页面滚动超出目标区域时,它的表现就像position:fixed;,它会固定在目标位置。元素定位表现为在跨越
·
sticky 英文字面意思是粘,粘贴,所以可以把它称之为粘性定位。
position: sticky; 基于用户的滚动位置来定位。
粘性定位的元素是依赖于用户的滚动,在 position:relative 与 position:fixed 定位之间切换。
它的行为就像 position:relative; 而当页面滚动超出目标区域时,它的表现就像 position:fixed;,它会固定在目标位置。
元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。
这个特定阈值指的是 top, right, bottom 或 left 之一,换言之,指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。
注意: Internet Explorer, Edge 15 及更早 IE 版本不支持 sticky 定位。 Safari 需要使用 -webkit- prefix (查看以下实例)。
<!!DOCTYPE html>
<html>
<header>
<meta charset="utf-8" />
<title>sticky定位验证</title>
<style>
*{
margin: 0;
padding: 0;
}
.body{
height: 200px;
overflow: scroll;
}
.mySticky{
background: lightgray;
position: sticky;
top: 0;
}
</style>
</header>
<body>
<div class="body">
<p class="mySticky">This is header A</p>
<p>This is content A</p>
<p>This is content A</p>
<p>This is content A</p>
<p>This is content A</p>
<p class="mySticky">This is header B</p>
<p>This is content B</p>
<p>This is content B</p>
<p>This is content B</p>
<p>This is content B</p>
<p class="mySticky">This is header C</p>
<p>This is content C</p>
<p>This is content C</p>
<p>This is content C</p>
<p>This is content C</p>
<p class="mySticky">This is header D</p>
<p>This is content D</p>
<p>This is content D</p>
<p>This is content D</p>
<p>This is content D</p>
</div>
</body>
</html>
标题行设置了背景色。如果不设置背景色(背景透明),正常文档流的文字就会和标题行文字重叠在一起显示。sticky定位的元素会遮住滚动而来的“正常”的文档流;后面的sticky元素会覆盖前面的sticky元素,就好像一层层的便利贴。
更多推荐
已为社区贡献7条内容
所有评论(0)