- static:默认值 不脱离文档流,top,right,bottom,left 等属性不生效,会随Html排版而移动位置。
- absolute:绝对定位,不会随排版而移动,会根据最近父位进行定位,元素会脱离正常文档流,不在占据空间。
- relative: 相对定位,会随Html排版而移动位置,还可通过top,right,bottom,left 调整位置。在它里面的absolute元素会根据relative去调整位置。
- fixed :固定定位,会定位到荧幕中间的固定位置,即使页面滚动,也会一直保持在那个位置,如果设置top,right,bottom,left,即便在relative中包裹,也只会根据页面,body去定位。
- sticky:粘性定位,专门用于页面滚动的时候的定位,可以方便实现吸顶条的效果。
<head> <style> .sticky{ position:sticky; width: 200px; height: 200px; left:900px; top: 0; background-color: rgb(51, 173, 124); } </style> </head> <body> <div class="sticky">sticky</div> </body> </html>
附视图代码:
<head>
<style>
.height{
width: 500px;
height: 200px;
background-color: aquamarine;
}
/* static默认属性 */
.static{
position: static;
width: 200px;
height: 200px;
background: rgb(217, 122, 122);
}
/* absolute */
.absolute{
width: 200px;
height: 200px;
background-color: rgb(77, 73, 73);
position: absolute;
left: 300px;
top: 20px;
}
.relative{
position: relative;
width: 200px;
height: 200px;
background-color: rgb(178, 16, 16);
left:400px;
bottom: 60px;
}
.fixed{
position: fixed;
width: 200px;
height: 200px;
left:600px;
bottom: 60px;
background-color: rgb(68, 52, 126);
}
</style>
</head>
<body>
<div class="height">height</div>
<div class="static">static</div>
<div class="absolute">absolute
<div class="absolute">absolute</div>
</div>
<div class="relative">
relative
</div>
<div class="fixed">
fixed
</div>
</body>
</html>