虽然会脱离文档流,可是不能排斥absolute定位,且其实在太强大css
先引用w3c对于 containing-block的说明css3
The position and size of an element’s box(es) are sometimes computed relative to a certain rectangle, called the containing block of the element. The containing block of a static or relative element is defined in the Box Model [CSS3BOX]. The containing block of a sticky element is the same as for a relative element. For fixed and absolute, it is defined as follows:bash
- If the element has position: fixed, the containing block is established by the viewport in the case of continuous media or the page area in the case of paged media.
- If the element has position: absolute, the containing block is established by the nearest ancestor with a position other than static, in the following way
即:当当前元素定位为absolute时,标准会赋予改元素一个 containing-block而该block的宽度和高度是由top、left、right、bottom来决定的spa
而absolute定位时,若是该元素显式设置了width和left和right则只会应用left和width,right会被忽略,同理应用于top、bottom、height3d
可是上述状况的一些应用会使人产生些思考: 以下代码:rest
<style>
.parent {
width: 100px;
height: 200px;
position: relative;
border: 1px solid #ddd;
background: linear-gradient(to right, green 0, green 70px, red 70px, red 100%);
background-size: 100%;
}
.children {
width: 50px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 30px;
background: #ccc;
margin: auto;
}
</style>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
复制代码
结果是: code
其实根据开头的引用,绿色区域其实就是containing-block的大小,而咱们设置了width则width小于了containing-block宽度,取自身宽度,而后再margin:auto天然就居中了。orm
说白了就是:containing-block 至关于在元素外围套了层div,且元素的左上角顶住containing-block的左上角。cdn
说多了很难理解,本身多改改代码天然就有深入体会了。blog
好比自行运行下面代码:
<style>
.parent {
width: 100px;
height: 200px;
position: relative;
border: 1px solid #ddd;
background: linear-gradient(to right, green 0, green 70px, red 70px, red 100%);
background-size: 100%;
}
.children {
width: 50px;
height: 50px;
position: absolute;
top: 0;
bottom: 10px;
left: 0;
right: 30px;
background: #ccc;
margin: auto;
}
</style>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
复制代码
至此前置知识准备完毕,这篇是本身查了stackoverflow和w3c标准得出的结论,对错与否不作保证,目前为止还与本身的认知没有出入。