它会根据用户的滚动位置在“相对定位”和“固定定位”之间切换。
工作原理:
- 指定粘性参考点:需要通过 top、right、bottom 或 left 属性指定一个粘性参考点。例如:top: 10px;。
- 初始行为:在没有达到指定的粘性参考点之前,元素会按照正常的文档流移动(相对定位的行为)。
- 达到参考点后:一旦滚动到指定的参考点(如 top: 10px),元素就会“粘住”在该位置,表现为固定定位(fixed)。
- 父级容器限制:position: sticky; 的效果受限于最近的块级滚动父容器。如果父容器的高度太小,粘性效果可能无法如预期工作。
position: sticky;
left: 0;
底部定位
测试代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>position: sticky 示例</title>
<style>
header {
background-color: lightblue;
padding: 10px;
position: sticky;
bottom: 0; /* 粘性参考点 */
}
article {
padding: 15px;
height: 2000px; /* 模拟长内容 */
background-color: #f9f9f9;
}
</style>
</head>
<body>
<article>
<p>向下滚动页面,观察导航栏的行为。</p>
</article>
<header>我是一个粘性导航栏</header>
</body>
</html>











网友评论