flexbox margin collapsing between children [duplic

2019-09-14 16:38发布

问题:

This question already has an answer here:

  • Margin collapsing in flexbox 2 answers

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>