flexbox margin collapsing between children [duplicate]

岁酱吖の 提交于 2020-01-25 22:02:28

问题


2 element inside a container with display:block margins collapse, but with display:flex is not working ! example

  .wrapper {
  width: 50%;
  margin: 0 auto;
}
.container {
  display: flex;
  // display: block;
  flex-flow: column nowrap;
  background-color: green;
}
h1 {
  background-color: #777;
  margin-bottom: 20px;
}
p {
  background-color: #ccc;
  margin-top: 15px;
}

回答1:


Margins does not collapse when one use display: flex. If you want to know more about collapse margins in general, here is a couple of articles to start with:

  • https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
  • https://css-tricks.com/what-you-should-know-about-collapsing-margins/

As a workaround, to make it behave similar to display: block, you could do something like this, where you add a flex class to container's that has display: flex, to target only h1 and p.

And if you can't do that manually, a script could do that work for you.

.wrapper {
  width: 50%;
  margin: 0 auto;
}
.container {
  display: flex;
  /* display: block; */
  flex-flow: column nowrap;
  background-color: green;
}
h1 {
  background-color: #777;
  margin-bottom: 20px;
}
p {
  background-color: #ccc;
  margin-top: 15px;
}


/* custom classes to remove margin */
.container.flex h1:first-child {
  margin-top: 0;
}
.container.flex p:last-child {
  margin: 0;
}
<div class="wrapper">
  <div class="container flex">
    <h1>header h1</h1>
    <p>plain text</p>
  </div>
</div>


来源:https://stackoverflow.com/questions/43466329/flexbox-margin-collapsing-between-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!