CSS-外邊距摺疊問題

外邊距摺疊

塊級元素的上外邊距和下外邊距有時會合並(或摺疊)爲一個外邊距,其大小取其中的最大者,這種行爲稱爲外邊距摺疊(margin collapsing),有時也翻譯爲外邊距合併。

  <!-- 外邊距摺疊演示 -->
  <div class="collapesd-test">
    <div id="top-div"></div>
    <div id="bottom-div"></div>
  </div>
     .collapesd-test {
      margin: 20px;
      border: 1px solid #808080;
    }

    #top-div {
      width: 50px;
      height: 50px;
      margin-bottom: 50px;
      background-color: #808080
    }

    #bottom-div {
      width: 100px;
      height: 100px;
      margin-top: 30px;
      background-color: #100100;
    }

以上代碼會產生外邊距摺疊問題,#top-div#bottom-div 之間分別定義了外邊距50px30px,而實際上加載時兩個div之間的邊距爲50px

這裏寫圖片描述

會發生外邊距摺疊的三種基本情況

相鄰元素之間
毗鄰的兩個元素之間的外邊距會摺疊(除非後一個元素需要清除之前的浮動)。
情況如上圖。

父元素與其第一個或最後一個子元素之間
如果在父元素與其第一個子元素之間不存在邊框、內邊距、行內內容,也沒有創建塊格式化上下文、或者清除浮動將兩者的 margin-top 分開;或者在父元素與其最後一個子元素之間不存在邊框、內邊距、行內內容、heightmin-heightmax-height將兩者的 margin-bottom 分開,那麼這兩對外邊距之間會產生摺疊。此時子元素的外邊距會“溢出”到父元素的外面。

  <!-- 父元素與子元素上下邊距摺疊 -->
  <div class="collapesd-test">
    <div id="father-div">
      <div id="child-div"></div>
    </div>
  </div>
    #father-div {
      background-color: #100100
    }

    #child-div {
      width: 50px;
      height: 50px;
      margin: 50px;
      background-color: #808080
    }

這裏寫圖片描述

空的塊級元素
如果一個塊級元素中不包含任何內容,並且在其 margin-topmargin-bottom 之間沒有邊框、內邊距、行內內容、height、min-height 將兩者分開,則該元素的上下外邊距會摺疊。

這裏寫圖片描述

解決方案:

1. 設置padding或者border

如果把div看做是細胞,paddingborder就好比細胞膜,因爲沒有東西阻隔外邊距之間互相滲透,導致摺疊。

舉第三種情況爲例,爲#empty-div添加padding屬性,即可避免外邊距摺疊。

CSS
#empty-div {
margin: 50px;
padding: 1px;
}

這裏寫圖片描述

2. 觸發BFC

BFC:塊格式化上下文(Block Formatting Context,BFC) 是Web頁面的可視化CSS渲染的一部分,是佈局過程中生成塊級盒子的區域,也是浮動元素與其他元素的交互限定區域。

簡單來說,BFC規定了內部塊級元素如何佈局。

以下方式都可以觸發BFC:

  • 根元素或包含根元素的元素(html
  • 浮動元素(元素的 float 不爲 none
  • 絕對定位元素(元素的 positionabsolutefixed
  • 行內塊元素(元素的 displayinline-block
  • 表格單元格(元素的 displaytable-cell,HTML表格單元格默認爲該值)
  • 表格標題(元素的 displaytable-caption,HTML表格標題默認爲該值)
  • 匿名錶格單元格元素(元素的 displaytabletable-row
    table-row-grouptable-header-grouptable-footer-group(分別是HTML
    tablerowtbodytheadtfoot的默認屬性)或 inline-table
  • overflow 值不爲 visible 的塊元素
  • display 值爲 flow-root 的元素
  • contain 值爲 layoutcontentstrict 的元素
  • 彈性元素(displayflexinline-flex元素的直接子元素)
  • 網格元素(displaygridinline-grid 元素的直接子元素)
  • 多列容器(元素的 column-countcolumn-width 不爲 auto,包括 column-count 爲 1)
  • column-spanall的元素始終會創建一個新的BFC,即使該元素沒有包裹在一個多列容器中(標準變更,Chrome bug)。

參考資料:
MDN

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章