边距在flexbox中崩溃 [英] Margin collapsing in flexbox

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

问题描述

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

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>

如您所见,即使在articlemain标签上都指定了20px的边距,您只能在最后一个 article 之间获得一个20px的边距.和 footer .

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.

但是,当使用 flexbox 时,我们在最后一个 article footer 之间得到一个40px边距-完整的20p x从文章到主体的边距,以及从主体到页脚的另一个20px.

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>

有没有一种方法可以使 flexbox 边距的行为与非flexbox相同?

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.

flex格式设置上下文中没有边际折叠 .

3. Flex容器:flexinline-flex display

flex容器为其建立新的flex格式化上下文 内容.这与建立块格式化上下文相同, 除了使用flex布局而不是块布局.例如, 浮标不会侵入flex容器,而flex 容器的边距不会随其内容的边沿而塌陷.

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.

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

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