4种定位分别是静态定位,相对定位,绝对定位,固定定位。有很多小伙伴分不太清楚绝对定位和相对定位。在下边我分别举例子说明一下。
1.position:static。静态定位,没有定位,当我们没有写定位的时候默认就是静态定位。不能通过4个方位名词改变位置也不能设置z-index。不脱离标准流。
2.position:relative。相对定位,这个相对是相当于自己的原来位置来说的。可以通过top,bottom,left,right移动位置也可以通过z-index设置层级。脱离标准流,并且移动之后,移动之前的位置还占有。
<style>
.o {
position: relative;
left: 50px;
top: 50px;
width: 100px;
height: 100px;
background-color: aqua;
}
.t {
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
<body>
<div class="o">相对定位 </div>
<div class="t">相对定位 </div>
</body>
定位前
定位后
可以看到第二个盒子并没有顶上去,第一个盒子相对于原来的位置向右下分别移动了50.
3.position:absolute。绝对定位。这个定位比较特殊,他的参照物是先寻找自己父级(广义,可以是父级的父级)除了static之外的有定位的,如果父级无其他定位,以浏览器为参照物。可以通过top,bottom,left,right移动位置也可以通过z-index设置层级。脱离标准流,并且移动之后,移动之前的 位置不存在。
1)父级有定位的情况,以父级为参照物移动
<style>
.box1 {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
.box2 {
position: absolute;
left: 50px;
top: 50px;
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
2)父级无定位的情况,以浏览器为参照物移动
<style>
.box2 {
position: absolute;
left: 50px;
top: 50px;
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
<body>
<div class="box2"></div>
</body>
绝对定位用的是最多的,记住一个词,子绝父相,我们在使用绝对定位时一般都给父亲设置一个相对定位。
4.position:fixed。固定定位。可以通过top,bottom,left,right移动位置也可以通过z-index设置层级。脱离标准流。相对于浏览器设置,一般用于导航栏,浏览器拖动,fixed定位不动。
如果遇到定位层级关系,可以通过z-index设置层级高低。不设置默认为0。