这是一个结合了 position:relative 和 position:fixed 两种定位功能于一体的特殊定位,适用于一些特殊场景。
当父元素部分滚动到”视线范围外”时,开始实现「fixed」的功能。当父元素整个不在“实现范围内”,取消「fixed」的功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sticky</title>
<style>
.parent {
display: flex; /*注释这个瞧瞧瞧瞧*/
}
.left {
background: red;
height: 500px;
width: 220px;
position: sticky;
top: 20px; /*须指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效*/
z-index: -1;
}
.right {
background: blue;
height: 1200px;
flex: 1;
}
</style>
</head>
<body>
<div style="height: 200px;"></div>
<div class="parent">
<div class="left">
</div>
<div class="right">
</div>
</div>
<div style="height: 1200px;"></div>
</body>
</html>