position:sticky
作用:relative+fixed的结合,制造出吸附效果。
再向上滚动页面的时候,有时我们想让某些元素在滚动一定距离之后固定在某个位置,这个时候就可以用这种定位方式。
效果:
滚动前:
滚动后:
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box1{
width: 100%;
height: 50px;
background: skyblue;
}
.box2{
width: 100%;
height: 50px;
background: darkorange;
position: sticky;
top: 0;
}
.box3{
width: 100%;
height: 1000px;
}
</style>
</head>
<body>
<div class="box1">这是一行文字</div>
<div class="box2">这是要固定的部分</div>
<div class="box3">
<p>主题部分</p><br />
<p>主题部分</p><br />
<p>主题部分</p><br />
<p>主题部分</p><br />
<p>主题部分</p><br />
<p>主题部分</p><br />
<p>主题部分</p><br />
<p>主题部分</p><br />
<p>主题部分</p><br />
<p>主题部分</p><br />
</div>
</body>
</html>