边缘在flexbox中折叠

时间:2017-05-10 02:55:58

标签: css css3 flexbox

通常,在CSS中,当父级及其最后一个子级具有边距时,边距会折叠以创建单个边距。 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>
&#13;
&#13;
&#13;

正如您所看到的,即使在20pxarticle标记上指定了main的边距,您也只会在最后一个标记之间获得20px页边距文章页脚

但是,在使用 flexbox 时,我们会在最后的文章页脚之间获得40px页边距 - 完整{{ 1}}从文章到main的x边距,以及从main到页脚的另一个20p

&#13;
&#13;
20px
&#13;
#container {
  display: flex;
  flex-direction: column;
}

article {
  margin-bottom: 20px
}

main {
  background: pink;
  margin-bottom: 20px;
}

footer {
  background: skyblue;
}
&#13;
&#13;
&#13;

有没有办法让 flexbox 边距的行为与非flexbox边缘相同?

5 个答案:

答案 0 :(得分:47)

保证金折叠是block formatting context的一项功能。

flex formatting context中没有边距折叠。

  

3. Flex Containers: the flex and inline-flex display values

     

Flex容器为其创建一个新的flex格式化上下文   内容。这与建立块格式化上下文相同,   除了使用flex布局而不是块布局。例如,   浮子不会侵入柔性容器和弯曲   容器的边距不会随其内容的边缘而崩溃。

答案 1 :(得分:2)

注意:这不是使边距在弹性框布局中的行为与在块布局中相同的方法;但是,这在某些情况下可能有助于解决保证金问题。

您可以使用伪选择器来获得想要的效果,而不必依靠折叠的边距:

main{
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

article{
  margin-bottom: 20px;
  background: #eee;
}

article:last-child{
  margin-bottom: 0;
}

footer{
  background: #eef;
}
<main>
  <article>
    This is article number 1
  </article>
  <article>
    This is article number 2
  </article>
  <article>
    This is article number 3
  </article>
</main>
<footer>
  This is the footer of the page
</footer>

答案 2 :(得分:2)

虽然使用 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

答案 3 :(得分:0)

已接受的答案说明了为什么它不起作用,但没有提供解决方案的原因。就像非flexbox示例一样,这是一种使flexbox元素对齐的方法。

#container {
  display: flex;
  flex-direction: column;
}

main {
  background: pink;
  margin-bottom: 20px;
}

main > article + article {
  margin-top: 20px
}

footer {
  background: skyblue;
}
<div id="container">
  <main>
    <article>
      Item 1
    </article>
    <article>
      Item 2
    </article>
  </main>
  <footer>Footer</footer>
</div>

答案 4 :(得分:0)

margin-trim可能会添加到css规范中,这将处理此类情况。在https://developer.mozilla.org/en-US/docs/Web/CSS/margin-trim中找到更多详细信息。可以在此处查看浏览器支持:https://caniuse.com/mdn-css_properties_margin-trim

相关问题