弹性框中的边距折叠

新手上路,请多包涵

通常,在 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 许可协议

阅读 375
2 个回答

边距折叠是 块格式化上下文 的一个特性。

flex 格式化上下文 中没有边距折叠。

3. Flex 容器: flexinline-flex display

弹性容器为其内容建立一个新的弹性格式化上下文。这与建立块格式化上下文相同,只是使用 flex 布局而不是块布局。例如,浮动不会侵入 flex 容器,并且 flex 容器的边距不会与其内容的边距一起折叠。

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 3.0 许可协议

虽然 flexbox 无法实现边距折叠,但您可以使用 gap 来实现相同的结果:

 .parent {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    column-gap: 5px;
    row-gap: 15px;

    max-width: 70px;
    outline: 1px solid #440;
}

.parent > div {
    background: #8ff;
    width: 20px;
    height: 20px;
}
 <div class="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

https://coryrylan.com/blog/css-gap-space-with-flexbox

原文由 oriadam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题