margin collpase(margin合并)小結

來源:互聯網
上載者:User

標籤:

一、前言

標題的margin collpase(margin 合并),江湖又成“margin 塌陷”;以前對margin 合并的理解就是在緊鄰的兄弟元素中上一個的margin-bottom會和下一個的margin-top合并;緊鄰父子項目,margin-top會合并;然後,就沒有然後了。直到實際項目中,看到已有項目中存在父子margin沒有合并的現象,但是自己又理解不了的時候,才人認真的將w3c中有關margin合并的規則看一遍。

二、margin collpase

margin collpase 規則

  1. root Element 不合并
  2. 相鄰(adjoining )margin合并為最大值

第一條中的root Element,即BFC,不知道BFC為何物的,待會兒請看下邊的相關連結,不過這個不影響下邊內容的理解

第二條中的相鄰(adjoing)的條件:(必須三條都滿足)

  1. 在同一個BFC中,且在文檔流中的區塊層級元素
  2. 相鄰的margin之間沒有行內元素(line boxes)、內邊距(padding)、邊框(border),如果是高度為0的行內元素無效如(空標籤<span><span>等)
  3. margin都是垂直方向

相鄰規則:

  1. top margin of a box and top margin of its first in-flow child(元素的margin-top以及它在文檔流中的第一個子項目的margin-top)
  2. bottom margin of box and top margin of its next in-flow following sibling(元素margin-bottom和它在文檔流中後邊緊鄰兄弟元素的margin-top)
  3. 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的)
  4. 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條,針對這兩條有兩種行之有效方法:

  1. 將元素轉變為BFC,具體查看BFC相關內容中的產生規則(當時在項目中看到的overflow:hidden就是符合這條原理)
  2. 將相鄰的margin切斷,從相鄰條件的三條中,我們可以看到,第2條還是可以阻止的。給元素添加padding,border。如果設計中沒有border,可以將border設定為透明(border-color:transparent;)

Technorati 標記: css

margin collpase(margin合并)小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.