CSS相对定位和绝对定位的区别
区别1:相对的对象不同
- 相对定位是相对于自己
- 绝对定位是相对于离自己最近的有定位的祖先
区别2:是否会脱离文档流
- 相对定位不会脱离文档流,不会影响其他元素的位置
- 绝对定位会脱离文档流,会影响其他元素的布局
代码演示
这是没有任何定位的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- -->
<style>
*{
margin: 0;
padding: 0;
}
.main{
position: relative;
width: 300px;
height: 400px;
margin: auto;
margin-top: 30px;
background-color: palegoldenrod;
}
.box1{
width: 200px;
height: 100px;
margin: auto;
margin-top: 10px;
background-color: palegreen;
}
.box2{
width: 200px;
height: 100px;
margin: auto;
margin-top: 10px;
background-color: palevioletred;
}
</style>
</head>
<body>
<div class="main">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>
运行结果:
给绿色容器加上相对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- -->
<style>
*{
margin: 0;
padding: 0;
}
.main{
position: relative;
width: 300px;
height: 400px;
margin: auto;
margin-top: 30px;
background-color: palegoldenrod;
}
.box1{
position: relative;
left: 50px;
width: 200px;
height: 100px;
margin: auto;
margin-top: 10px;
background-color: palegreen;
}
.box2{
width: 200px;
height: 100px;
margin: auto;
margin-top: 10px;
background-color: palevioletred;
}
</style>
</head>
<body>
<div class="main">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>
给绿色容器加入相对定位:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- -->
<style>
*{
margin: 0;
padding: 0;
}
.main{
position: relative;
width: 300px;
height: 400px;
margin: auto;
margin-top: 30px;
background-color: palegoldenrod;
}
.box1{
position: absolute;
left: 50px;
width: 200px;
height: 100px;
margin: auto;
margin-top: 10px;
background-color: palegreen;
}
.box2{
width: 200px;
height: 100px;
margin: auto;
margin-top: 10px;
background-color: palevioletred;
}
</style>
</head>
<body>
<div class="main">
<div class="box1"></div>
<div class="box2"></div>
</div>
</body>
</html>