<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1{
width: 200px;
height: 200px;
background-color: aqua;
}
.box2{
width: 200px;
height: 200px;
background-color: bisque;
}
.box4{
width: 400px;
height: 400px;
background-color: blueviolet;
}
.box5{
width: 300px;
height: 300px;
background-color: beige;
}
</style>
</head>
<body>
<div class="box1">1</div>
<div class="box4">4
<div class="box5">
5
<div class="box2">2</div>
</div>
</div>
</body>
</html>
运行结果:
绝对定位的特点:
1.开启绝对定位后,如果不设置偏移量 元素的位置不会发生改变
2.开启绝对定位后,元素会从文档流中脱离
3.绝对定位会改变元素的性质,行内变成块,块的宽高被内容撑开
4.绝对定位会使元素提升一个层级
5.绝对定位是相对于其包含块进行定位的
包含块:
正常情况下:
包含块就是离当前元素最近的祖先块级元素
绝对定位的包含块:
包含块就是离它最近的开启了定位的祖先元素,如果所有的祖先元素都没有开启定位则根元素就是它的包含块
例如:
给box2加上绝对定位 其他元素没有开启定位 则:box2相对于根元素进行定位
给box2加绝对定位的同时 给box4加上相对定位 则:box2相对于box4元素进行定位
给box2加绝对定位的同时 给box4和box5都加上相对定位 则:box2相对于box5元素进行定位