通常,在 CSS 中,当父级及其最后一个子级有边距时,边距会折叠以创建单个边距。例如
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>
如您所见,即使在 article
和 main
标签上指定了 20px
的边距,您也只会得到一个最后一个文章和页脚之间的20px
边距。
然而,当使用 flexbox 时,我们在最后一个 article 和 footer 之间得到一个 40px
边距——一个从文章到主体的完整 20p
x 边距,从主体到 页脚 的另一个 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 的一样?
最佳答案
边距折叠是 block formatting context 的一个特征.
flex formatting context 中没有边距崩溃.
3. Flex Containers: the
flex
andinline-flex
display
valuesA flex container establishes a new flex formatting context for its contents. This is the same as establishing a block formatting context, except that flex layout is used instead of block layout. For example, floats do not intrude into the flex container, and the flex container’s margins do not collapse with the margins of its contents.
关于css - flexbox 中的边距折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448986/