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/56448986/

相关文章:

html - 我想选择除特定节点的所有后代之外的所有节点

html - Flexbox 导航的全宽不起作用

html - Flexbox:每行 4 个元素

jquery - 从右到左悬停 div 的按钮 Onclick 在我的 JSP 页面上不起作用。

php - 使用 PHP 和 MySQL 进行列行对齐

html - 尝试在嵌套的 <li> 样式菜单中选择 CSS3 元素

html - CSS - 填充可用问题

html - 如何使用 bootstrap 使图像和文本垂直居中?

html - flex 容器的非直接子子项似乎在垂直方向上未对齐。为什么?

css - 如何防止 CSS NOT 选择器更改子元素的父元素