通常,在 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>
As you can see, even though a margin of 20px
is specified on both the article
and the main
tags, you only get a 20px
最后 一篇文章 和 页脚 之间的边距。
然而,当使用 flexbox 时,我们在最后 一篇文章 和 页脚 之间得到一个 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 的一样?
原文由 Coffee Bite 发布,翻译遵循 CC BY-SA 4.0 许可协议
边距折叠是 块格式化上下文 的一个特性。
在 flex 格式化上下文 中没有边距折叠。