css - flexbox 中的边距折叠

标签 css flexbox

通常,在 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>

如您所见,即使在 articlemain 标签上指定了 20px 的边距,您也只会得到一个最后一个文章页脚之间的20px边距。

然而,当使用 flexbox 时,我们在最后一个 articlefooter 之间得到一个 40px 边距——一个从文章到主体的完整 20px 边距,从主体到 页脚 的另一个 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 and inline-flex display values

A 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/58130397/

相关文章:

html - 动态共享多个元素之间的宽度?

html - 滚动条无法出现在两个 flexbox 容器中

html - 图像的多种背景颜色

javascript - 按钮函数 OpenInNewTab 在 <figcaption> 中无法正常工作

html - Outlook 电子邮件客户端 : pointer-events:none

html - 将 vh 与 flexbox 一起使用时如何修复 Component-Streching?

css - Flex 在较大的断点处包裹元素,而在最小处滚动溢出

javascript - jQuery:防止 child 继承 parent 的属性?

css - 在一个 div 中打印一个 div

html - 使 flex 列表元素在较小的屏幕上交错成多行