position:absolute 绝对定位
绝对定位脱离文档流,需要有一个参照物才可以定位,它是相对于最近拥有定位属性的父元素进行定位的,如果找不到则相对于body浏览器窗口进行定位。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>绝对定位 absolute</title>
<style>
.box1 {
width: 500px;
height: 500px;
margin: 150px auto;
background-color:aquamarine;
border: 1px solid #000;
}
.box2 {
width: 200px;
height: 200px;
background-color: cornflowerblue;
}
.box3 {
width: 200px;
height: 200px;
background-color: rgb(241, 155, 26);
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
</html>
利用定位属性让box1盒子距离上面30 左边80
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>绝对定位 absolute</title>
<style>
.box1 {
width: 500px;
height: 500px;
margin: 150px auto;
background-color:aquamarine;
border: 1px solid #000;
position: relative; /*相对定位,不脱离文档流,如果想让box2在box1中定位就需要给父元素设置相对定位*/
}
.box2 {
width: 200px;
height: 200px;
background-color: cornflowerblue;
position: absolute; /* 绝对定位 脱离文档流,不占原先的位置 */
top:30px;
left: 80px;
}
.box3 {
width: 200px;
height: 200px;
background-color: rgb(241, 155, 26);
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
</html>
因为绝对定位是 脱离文档流的不占位置的, 所以box3的盒子就自动上去了,如果子元素想在容器中用绝对定位absolute进行定位时,就必须要给最近的父元素设置相对定位relative(不脱离文档流),如果父元素也设置绝对定位的话,就是相对于body进行定位了。