以前一直对绝对定位下的margin作用很模糊,今天细看一下
不使用top,left,margin等
<!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>Document</title><style>.container{position: relative;border: 1px solid blue;width: 500px;height: 500px;margin: 100px auto;}.child{position: absolute;width: 100px;border:1px solid red;height: 100px;}.before{display: inline-block;width: 100px;height: 100px;border: 1px solid black;}</style>
</head>
<body><div class="container"><span class="before">1212</span><span class="child">22 </span></div>
</body>
</html>
可以看出,自然状态下,绝对定位元素参照标准流位置,紧邻before元素
只定义left、top不使用margin
.child{position: absolute;width: 100px;border:1px solid red;height: 100px;top:10px;left: 10px;}
可看出定位元素是相对于使用了定位的父级元素
只使用margin
.child{position: absolute;width: 100px;border:1px solid red;height: 100px;margin-left: 10px;}
可以看到它是根据未用position定位的before元素的边界进行margin定位的,对margin-top同样适用
margin与left/top结合
.child{position: absolute;width: 100px;border:1px solid red;height: 100px;margin-left: 70px;left: 50px;}
可以看出定位元素是相对于父级进行了定位的元素进行定位的,margin-left+left=120px,对margin-top同样适用
总结
1、只使用left等定位是按照上层相对定位(或绝对定位)的边界进行定位
2、只使用margin相关属性定位时按照上层标准流(或浮动)块的边界进行定位
3、当同时使用两者时则按照上层相对定位(或绝对定位)的边界进行定位,并且距离值为两者的相加值
4、对于不使用left也没有margin的,自动按照上层标准流进行定位
#con{ position:absolute; left:50%; width:760px; margin-left:-380px;
}
使用绝对定位与margin是有道理的