<!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>
* {
margin: 0;
padding: 0;
}
.div1 {
width: 200px;
height: 200px;
background-color: teal;
position: relative;
}
.div2 {
width: 100px;
height: 100px;
background-color: tomato;
position: absolute;
margin-top: 100px;
margin-left: 100px;
}
</style>
</head>
<body>
<div class="div1">
<div class="div2"></div>
</div>
</body>
</html>
如果div1里面包着div11 div11里面包着div111
子绝父相:给div1设置 相对定位
给div11设置 绝对定位 div11会根据div1的左上角为0点移动 (top left)
如果要移动div111 前面都不用动 给div111设置绝对定位 top left的值 是以他的父元素 div11的左上角为原点移动
如果再有一个与div1同级的元素div2 想移动它 前面几个元素依然还想保留 只需要给div2设置绝对定位 但是此时div2是以页面视口区 也就是body的左上角为起点 用top left移动
<!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>
* {
margin: 0;
padding: 0;
}
.div1 {
width: 300px;
height: 300px;
background-color: tomato;
position: relative;
}
.div11 {
width: 200px;
height: 200px;
background-color: turquoise;
position: absolute;
top: 100px;
}
.div12 {
width: 200px;
height: 200px;
background-color: violet;
position: absolute;
left: 200px;
}
.div111 {
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
top: 100px;
left: 200px;
}
.div2 {
width: 300px;
height: 300px;
background-color: steelblue;
position: absolute;
top: 300px;
left: 300px;
}
</style>
</head>
<body>
<div class="div1">
<div class="div11">
<div class="div111"></div>
</div>
<div class="div12"></div>
</div>
<div class="div2"></div>
</body>
</html>