弹性盒中的边距折叠 [英] Margin collapsing in flexbox

查看:16
本文介绍了弹性盒中的边距折叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在 CSS 中,当父级及其最后一个子级有边距时,边距会折叠以创建单个边距.例如

article {底部边距:20px}主要的 {背景:粉红色;底边距:20px;}页脚{背景:天蓝色;}

<主要><文章>第 1 项</文章><文章>第 2 项</文章></main><页脚>页脚</页脚>

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

然而,当使用 flexbox 时,我们在最后一篇 文章footer 之间获得了 40px 边距——一个从文章到正文的完整 20px 边距,以及从正文到 footer 的另一个 20px 边距.

#container {显示:弹性;弹性方向:列;}文章 {底部边距:20px}主要的 {背景:粉红色;底边距:20px;}页脚{背景:天蓝色;}

<主要><文章>第 1 项</文章><文章>第 2 项</文章></main><页脚>页脚</页脚>

有没有办法让 flexbox 边距的行为与非 flexbox 的一样?

解决方案

Margin collapsing 是 块格式上下文.

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

<块引用>

3.Flex 容器:flexinline-flex display价值观

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

Typically, in CSS, when a parent and its last child have a margin, the margins collapse to create a single margin. E.g.

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 margin between the last article and footer.

When using flexbox, however, we get a 40px margin between the last article and footer — a full 20px margin from the article to main, and another 20px from main to footer.

#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>

Is there a way to make flexbox margins behave the same way as the non-flexbox ones?

解决方案

Margin collapsing is a feature of a block formatting context.

There is no margin collapsing in a 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.

这篇关于弹性盒中的边距折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆