雖然會脫離文檔流,可是不能排斥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標準得出的結論,對錯與否不作保證,目前爲止還與本身的認知沒有出入。