標籤:
一、前言
標題的margin collpase(margin 合并),江湖又成“margin 塌陷”;以前對margin 合并的理解就是在緊鄰的兄弟元素中上一個的margin-bottom會和下一個的margin-top合并;緊鄰父子項目,margin-top會合并;然後,就沒有然後了。直到實際項目中,看到已有項目中存在父子margin沒有合并的現象,但是自己又理解不了的時候,才人認真的將w3c中有關margin合并的規則看一遍。
二、margin collpase
margin collpase 規則
- root Element 不合并
- 相鄰(adjoining )margin合并為最大值
第一條中的root Element,即BFC,不知道BFC為何物的,待會兒請看下邊的相關連結,不過這個不影響下邊內容的理解
第二條中的相鄰(adjoing)的條件:(必須三條都滿足)
- 在同一個BFC中,且在文檔流中的區塊層級元素
- 相鄰的margin之間沒有行內元素(line boxes)、內邊距(padding)、邊框(border),如果是高度為0的行內元素無效如(空標籤<span><span>等)
- margin都是垂直方向
相鄰規則:
- top margin of a box and top margin of its first in-flow child(元素的margin-top以及它在文檔流中的第一個子項目的margin-top)
- bottom margin of box and top margin of its next in-flow following sibling(元素margin-bottom和它在文檔流中後邊緊鄰兄弟元素的margin-top)
- bottom margin of a last in-flow child and bottom margin of its parent if the parent has ‘auto‘ computed height(文檔流中最後一個子項目的margin-bottom和它父元素的margin-bottom,前提是,父元素的height是auto的)
- top and bottom margins of a box that does not establish a new block formatting context and that has zero computed ‘min-height‘, zero or ‘auto‘ computed ‘height‘, and no in-flow children(非BFC元素的margin-top和margin-bottom,並且這個元素的min-height為0,height為0或者auto,且沒有文檔流內的子項目)
margin負值合并規則:
When two or more margins collapse, the resulting margin width is the maximum of the collapsing margins‘ widths. In the case of negative margins, the maximum of the absolute values of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the maximum of the absolute values of the adjoining margins is deducted from zero.(多個margin合并的時候,合并得到的是最大值。如果margin是負值,正值最大的margin減去負值絕對值最大margin的絕對值就是最終margin;如果沒有正值margin,結果就是0減去負值絕對值最大margin絕對值)
三、阻止margin collpase
上邊的margin collpase規則是2條,針對這兩條有兩種行之有效方法:
- 將元素轉變為BFC,具體查看BFC相關內容中的產生規則(當時在項目中看到的overflow:hidden就是符合這條原理)
- 將相鄰的margin切斷,從相鄰條件的三條中,我們可以看到,第2條還是可以阻止的。給元素添加padding,border。如果設計中沒有border,可以將border設定為透明(border-color:transparent;)
Technorati 標記: css
margin collpase(margin合并)小結