2017-05-10 93 views
7

通常,在CSS中,當父級和其最後一個子級具有邊距時,邊距會摺疊以創建單個邊距。例如。Flexbox中的邊距摺疊

article { 
 
    margin-bottom: 20px 
 
} 
 

 
main { 
 
    background: pink; 
 
    margin-bottom: 20px; 
 
} 
 

 
footer { 
 
    background: skyblue; 
 
}
<div id="container"> 
 
    <main> 
 
    <article> 
 
     Item 1 
 
    </article> 
 
    <article> 
 
     Item 2 
 
    </article> 
 
    </main> 
 
    <footer>Footer</footer> 
 
</div>

正如你可以看到,即使在articlemain標籤都被指定的20像素的保證金,你只能得到最後一篇文章和頁腳之間的20像素的保證金。

當使用Flexbox的,但是,我們得到了最後一篇文章和頁腳之間的保證金40點 - 從文章主要一個完整的20像素的保證金,並從主要另一爲20px到頁腳。

#container { 
 
    display: flex; 
 
    flex-direction: column; 
 
} 
 

 
article { 
 
    margin-bottom: 20px 
 
} 
 

 
main { 
 
    background: pink; 
 
    margin-bottom: 20px; 
 
} 
 

 
footer { 
 
    background: skyblue; 
 
}
<div id="container"> 
 
    <main> 
 
    <article> 
 
     Item 1 
 
    </article> 
 
    <article> 
 
     Item 2 
 
    </article> 
 
    </main> 
 
    <footer>Footer</footer> 
 
</div>

有沒有一種方法,使Flexbox的利潤的行爲方式作爲非Flexbox的那些一樣嗎?

回答

10

保證金摺疊是block formatting context的一項功能。

flex formatting context沒有保證金摺疊。

3. Flex Containers: the flex and inline-flexdisplay values

Flex容器確立了其 內容的新的Flex格式化的內容。這與建立塊格式上下文 相同,除了使用彈性佈局而不是塊佈局。例如, 浮標不會侵入柔性容器,而容器的邊距不會因其內容的邊距而摺疊。

+3

nnnnnooooooooooooooo不要告訴我這個!我如何擺脫模塊之間的額外空間? –

+0

@TomRoggero可能會爲該內容添加一個包裝以在塊格式上下文中工作?包裝器然後存在於flex格式化上下文中,但不是它的內容 - 我猜想。但是,包裝往往會打破良好的語義標記。 –