小编典典

边距在flexbox中崩溃

css

通常,在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>

如您所见,即使20pxarticlemain标记上都指定了的边距,您也只能20px在最后 一篇文章页脚 之间得到一个边距。

但是,当使用 flexbox 时,我们40px在上一个 文章页脚 之间 留有 边距- 20p从文章到main
的全边距为x,20px从main到 footer的 边距为全x 。

#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的 边距相同?


阅读 360

收藏
2020-05-16

共1个答案

小编典典

边距折叠是 块格式化上下文的功能

在[ flex格式化环境中 没有边际崩溃。

3. Flex容器:flexinline-flex display

一个伸缩容器为其内容建立一个新的伸缩格式上下文。这与建立块格式化上下文相同,除了使用Flex布局而不是块布局。例如,浮点数不会侵入flex容器,并且flex容器的边距不会随其内容的边沿收缩。

2020-05-16