要注意的两个点,不然粘性布局会失效:
1、粘性元素的父元素或者父元素的父元素等(总之就是直系长辈元素)任意一个设置overflow:hidden;overflow-x: hidden; overflow-y: hidden;overflow:auto;overflow-x:auto;overflow-y:auto;的任意一种时,就会不生效。
2、父元素的高度小于设置sticky元素的高度时,sticky也失效。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>粘性布局</title>
<style>
body{
height: 2000px;
}
.box1{
height: 100vh;
background-color: pink;
}
.box2{
height: 2000px;
background-color: aquamarine;
}
.sticky{
height: 100vh;
position: sticky;
position: -webkit-sticky;
top: 0;
background-color: blueviolet;
}
.box3{
height: 100vh;
background-color: bisque;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2">
<div class="sticky"></div>
</div>
<div class="box3"></div>
</body>
</html>