0

This is a problem I never understood. Lets say I have a container and one or several divs in the container. When the last item has a margin-bottom it does not increase the size of the container, if the container does not have a padding-bottom or border.

The example shows some workaround but I have no idea why the browser or spec behaves like that.

.item {
  height: 20px;
  background: red;
  margin-bottom: 10px;
}

.container {
  padding: 10px;
  padding-bottom: 0;
  background: blue;
  margin-bottom: 20px;
}

.container2 {
  padding: 10px;
  padding-bottom: 0.1px;
  background: green;
  margin-bottom: 20px;
}

.container3 {
  padding: 9px;
  padding-bottom: 0;
  border: 1px solid green;
  background: green;
  margin-bottom: 20px;
}
<div class="container">
  <div class="item">
  </div>
  
  <div class="item">
  </div>

  <div class="item">
  </div>
</div>

<div class="container2">
  <div class="item">
  </div>
  
  <div class="item">
  </div>

  <div class="item">
  </div>
</div>

<div class="container3">
  <div class="item">
  </div>
  
  <div class="item">
  </div>

  <div class="item">
  </div>
</div>
SebastianStehle
  • 2,235
  • 1
  • 21
  • 30
  • 1
    https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing. And the best/easiest solution to get the result you're after is to set `overflow:auto` on the container. – j08691 Nov 16 '18 at 16:30
  • 1
    https://www.w3.org/TR/CSS2/box.html#collapsing-margins – Fabrizio Calderan Nov 16 '18 at 16:31
  • 2
    Per the MDN on Margin Collapsing (which @j08691 linked above): *"If there is **no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse**. The collapsed margin ends up outside the parent."* – Tyler Roper Nov 16 '18 at 16:31
  • Fast answer, thank you, super strange behavior in my opinion. – SebastianStehle Nov 16 '18 at 16:33

0 Answers0