区别相对定位和绝对定位
1.相对定位
1.1定义:
相对定位就是相对于自己原来的位置进行偏移
1.2案例:
1)没有加position时候
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>相对定位和绝对定位</title>
<style>
.p1{
background-color: #2aabd2;
width: 100px;
height: 100px;
}
.p2{
background-color: #f0ad4e;
width: 100px;
height: 100px;
}
.p3{
background-color: #3c763d;
width: 100px;
height: 100px;
}
.p4{
background-color: #0000FF;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div>
<p class="p1">1</p>
<p class="p2">2</p>
<p class="p3">3</p>
<p class="p4">4</p>
</div>
</body>
</html>
2)效果:
3)给p1增加相对定位:
.p1{
background-color: #2aabd2;
width: 100px;
height: 100px;
/* 相对定位*/
position: relative;
top: 30px;
left: 50px;
}
4)效果:
说明:1号蓝色方块相对自己的位置进行了偏移,灰色方框是1号之前的位置,他的改变,不会影响其他元素的位置变化,重叠部分,则会覆盖2号方块。
2.绝对定位
2.1定义:
相对于父元素进行偏移,找离自己最近的position: relative 相对定位元素作为参照,如果没有找到的,就以整个浏览器为参照位置。
2.2代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绝对定位</title>
<style>
.p1{
background-color: #2aabd2;
width: 80px;
height: 80px;
}
.p2{
background-color: #f0ad4e;
width: 80px;
height: 80px;
}
.p3{
background-color: #3c763d;
width: 80px;
height: 80px;
}
.p4{
background-color: #0000FF;
width: 80px;
height: 80px;
position: absolute;
top: 30px;
right: 20px;
}
.d1{
position: relative;
width: 200px;
height: 600px;
background-color: #8a6d3b;
}
.d2{
position: relative;
width: 160px;
height: 550px;
background-color: yellow;
}
.d3{
width: 130px;
height: 400px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div class="d1">
<div class="d2">
<div class="d3">
<div class="p1"><p>1</p></div>
<div class="p2"><p>2</p></div>
<div class="p3"><p>3</p></div>
<div class="p4"><p>4</p></div>
</div>
</div>
</div>
</body>
</html>
2.3效果:
说明:决定定位的效果,会影起其他元素的移动,自动补齐位置。