定位具体规则
定位
相对定位
相对于自己原来的位置
绝对定位
1 绝对定位的定位规则:相对与最近一级有定位(绝对定位,相对定位,固定定位)的祖先元素
2 具体值的定位原则:首先找到具有定位的祖先元素,然后该元素的最外边(可能是上top/下bottom/左left/右right),包含margin值,距离祖先盒子的内边(对应的上下左右),包含padding,不含border的距离为这个值
eg: 给了绝对定位,top值为10px;那么这个盒子顶部的最外边缘,将距离有定位的祖先元素的顶部内边缘10px
3 正负问题:我们知道了为0时候的位置,边界;那么绝对定位的盒子相对于边界往相对定位盒子的里面移动为正,相反为负;(就是说,我们可以先找到边界值,为零时候的样子,然后,如果值为正,绝对定位的盒子向方位词(top/bottom/left/right)相反的方向移动,为负则往相同方向移动)
eg:top:10px;那么绝对定位的盒子的最上边缘一定在具有定位祖先元素的上边缘(含padding,不含border)的下方(为正);且距离为10px
<!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>
.dad {
position: relative;
width: 200px;
height: 200px;
border: 10px solid green;
}
.son {
position: absolute;
right: -100px;
bottom: 100px;
width: 100px;
height: 100px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="dad">
<div class="son"></div>
</div>
</body>
</html>
效果图1
现在我该子盒子添加了margin
.dad {
position: relative;
width: 200px;
height: 200px;
border: 10px solid rgb(94, 221, 136)
}
.son {
position: absolute;
bottom: 0px;
right: -100px;
width: 100px;
height: 100px;
border: 4px solid red;
background-color: rgb(106, 206, 219);
margin-bottom: 10px;
}
效果图2
或者理解为绝对定位的盒子从border最外边到相对盒子的定位,然后加上padding后的效果
固定定位
相对定位是相对于浏览器可视区域
也是盒子最外边,包括padding;或者理解为border外边定位后,在加上padding值后的效果;相对与浏览器可视区的定位