写在前面:
这篇文章其实还是没有谈到为什么绝对定位元素可以设置margin,以及为什么margin设置时的参照物是经过绝对定位后的位置,但是阅读后可以快速掌握绝对定位下的margin应该怎么设置。
1. 总体规则
对于绝对定位元素
-
若设置了top和left,则margin-top和margin-left有移动效果
设置margin-bottom和margin-right会占据空间,但是无移动效果
若设置了bottom和right,则margin-bottom和margin-right有移动效果
设置margin-top和margin-left会占据空间,但是无移动效果
-
设置margin时的参照物为,在定位结束后的位置
2. 关于position:absolute确定具体位置时的细节
把top,bottom,right,left看成坐标轴,坐标轴围成的范围是在设置数值时的参照物
eg1.设置top,left
eg2.设置bottom,right
3. 绝对定位后,设置margin,margin的参照物
定位后,设置前:
定位后,设置后:
无明显效果,但是会占据空间
设置后相对与参照线进行移动,正负都可以
4. 实例
.a{
width: 200px;
height: 200px;
position: relative;
background-color: black;
margin: 100px;
}
.b{
position: absolute;
width: 50px;
height: 50px;
bottom: 100%;
right: 50%;
background-color: red;
margin-left: 0px;
margin-right: -15px;
margin-top: 0px;
margin-bottom: 15px;
}
<div class="a">
<div class="b"></div>
</div>
若文章有误,欢迎指正