postion
- static:正常布局;top,right,bottom,left,z-index属性失效
- relative:相对定位
- absolute:绝对定位,相对最近一个非static祖先元素定位;脱离文档流(以及float属性)
- fixed:固定定位,相对于屏幕视口(viewport)的位置来指定元素位置,页面滚动位置也固定;脱离文档流
- sticky:粘性定位,先按照relative定位,再按照fixed定位 粘性定位是相对定位和fixed固定定位的混合,元素在跨域特定阈值前为相对定位,之后为固定定位。
以下元素就是 sticky定位,当距离视口viewport滚动到元素top距离小于10px之前,元素为相对定位,之后元素将一直 fixed定位距离视口top:20px的位置。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style type="text/css">
* {
margin: 0;
padding: 0
}
html body {
height: 100vh;
width: 100%
}
h1 {
height: 200px;
position: relative;
background-color: lightblue;
}
h1:after {
content: '';
position: absolute;
top: 100px;
left: 0;
width: 100%;
height: 2px;
background-color: red;
}
#sticky-nav {
position: sticky;
/*position: absolute;*
left: 0;*/
top: 10px;
width: 100%;
height: 80px;
background-color: yellowgreen;
}
.scroll-container {
height: 600px;
width: 100%;
background-color: lightgrey;
}
</style>
<body>
<h1>高200px;距顶部100px</h1>
<div id="sticky-nav">这是一个tab切换栏,给sticky定位top=100px</div>
<p class="scroll-container">发生滚动</p>
<p class="scroll-container" style="background:lightgoldenrodyellow;">发生滚动</p>
</body>
</html>