position定位元素有相对定位、绝对定位、固定定位、粘性定位
position定位可以用来进行网页布局
1、相对定位:
相对于原先位置进行定位,在没有设置定位属性的情况下,默认在当前位置 。
相对定位不脱离文档流, 原先位置保留。
2、绝对定位:
如果有定位祖先元素,相对于离该元素最近的定位祖先元素进行定位, 如果没有定位祖先元素,相对于视口区定位。如果没有设置定位属性,那么在原来位置显示。
绝对定位脱离文档流,原先位置不保留。
3、固定定位
固定在视口区的某一位置,原来位置不保留,如果没有设置定位属性那么在原来位置固定定位
固定定位脱离文档流,原先位置不保留
4、粘性定位
结合相对定位和固定定位效果。刚开始是相对定位的效果,然后页面滚动到合适的位置,变成固定定位。没有设置定位属性的情况下,在原先位置显示
粘性定位不脱离文档流,原先位置保留
代码:
<body>
<div class="one">相对定位</div>
<div class="two">绝对定位</div>
<div class="three">固定定位</div>
<div class="four">粘性定位</div>
</body>
<style>
.one {
width: 100px;
height: 150px;
background-color: plum;
position: relative;
}
.two {
width: 100px;
height: 150px;
background-color: palegreen;
position: absolute;
top: 30px;
left: 30px;
}
.three {
width: 100px;
height: 150px;
background-color: slateblue;
position: fixed;
bottom: 50px;
left: 50px;
}
.four {
width: 100px;
height: 150px;
background-color: yellow;
position: sticky;
top: 100px;
left: 50px;
}
</style>
结果图: