position: sticky轻松做出吸顶功能
sticky
sticky元素根据正常文档流进行定位,然后相对它的最近滚动祖先和最近块级祖先,基于top, right, bottom, 和 left的值进行偏移。偏移值不会影响任何其他元素的位置。
粘性定位可以被认为是相对定位和固定定位的混合。元素在跨越特定阈值前为相对定位,之后为固定定位。
由于这个特殊的性质,所以可以轻松的实现吸顶的功能
注意:须指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
<style>
.container {
position: relative;
}
.container img {
width: 100%;
height: auto;
}
.bg {
position: absolute;
top: 0px;
bottom: 0px;
width: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.h3 {
position: -webkit-sticky;
position: sticky;
top: 0;
z-index: 1;
height: 100px;
line-height: 100px;
background-color: #fff;
}
</style>
</head>
<body>
<div class="container">
<img src="https://seopic.699pic.com/photo/50062/8783.jpg_wh1200.jpg" />
<div class="bg"></div>
</div>
<div class="container">
<img src="https://seopic.699pic.com/photo/50062/8783.jpg_wh1200.jpg" />
<div class="bg"></div>
</div>
<h3 class="h3">粘性div</h3>
<div class="container">
<img src="https://seopic.699pic.com/photo/50062/8783.jpg_wh1200.jpg" />
<div class="bg"></div>
</div>
<div class="container">
<img src="https://seopic.699pic.com/photo/50062/8783.jpg_wh1200.jpg" />
<div class="bg"></div>
</div>
<div class="container">
<img src="https://seopic.699pic.com/photo/50062/8783.jpg_wh1200.jpg" />
<div class="bg"></div>
</div>
<div class="container">
<img src="https://seopic.699pic.com/photo/50062/8783.jpg_wh1200.jpg" />
<div class="bg"></div>
</div>
<script src="" async defer></script>
</body>
</html>
效果如下: