CSS相对定位和绝对定位的区别
最编程
2024-07-10 07:13:23
...
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>
上一篇: AJAX学习笔记上(学习自用)
下一篇: 源码编译安装 LAMP
推荐阅读
-
CSS绝对定位和相对定位和子绝父相
-
网页前端 CSS进阶布局技巧(二):详解5.3 子元素相对定位与父级元素的关系(子绝父相)
-
理解CSS中的子元素超越父级布局:从相对定位开始讲解
-
CSS技巧讲解⑤:子元素与父元素的定位配合 - 绝对定位与相对定位实例展示
-
深入理解 CSS 中的相对定位 (relative) 与绝对定位 (absolute): 详解两者的区别与用法
-
在CSS中理解并运用子元素的绝对定位与父级元素的相对定位(子绝父相)
-
CSS布局技巧:定位方法详解 - 相对定位、绝对定位、子元素与父容器的定位模式、固定定位,以及它们之间的层级关联
-
CSS里的两种定位方式:绝对定位与相对定位详解
-
HTML里的相对定位与绝对定位:一探究竟
-
理解与应用:儿子超越父亲的技巧 - 相对定位与绝对定位的解析