2

Hello, why margin bottom of child not increasing the height of parent:

<div class="my-container">
<div class="margin">
    Hello World
</div>
<div class="margin">
    Hello World
</div>

.my-container {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
width: 300px;
background-color: #3873fe;
margin: auto;
}

.my-container .margin {
    width: 100px;
    margin: 0 auto 50px;
    background-color: #00ff82;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

enter image description here

But if add border for parent, the height of parent will increased:

.my-container {
    border:1px solid;
}

enter image description here

So I'd like to understand why this difference?

Michael Neas
  • 231
  • 1
  • 15

2 Answers2

5

You need to add overflow: auto; to the parent div.

.my-container {
  overflow: auto;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 300px;
  background-color: #3873fe;
  margin: auto;
}

.my-container .margin {
  width: 100px;
  margin: 0 auto 50px;
  background-color: #00ff82;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
<div class="my-container">
  <div class="margin">
    Hello World
  </div>
  <div class="margin">
    Hello World
  </div>
</div>
athi
  • 1,683
  • 15
  • 26
Troyer
  • 6,765
  • 3
  • 34
  • 62
  • Thank you, I know the solution but I'd like to know what is the reason?! – Michael Neas May 02 '17 at 09:24
  • The problem as @Pete told us is collapsing margins, you can have more information about there: http://stackoverflow.com/questions/3069921/what-is-the-point-of-css-collapsing-margins – Troyer May 02 '17 at 09:26
  • @MichaelNeas If my answer was the correct one you can mark it as the correct answer. :) – Troyer May 02 '17 at 09:44
0

Use display: inline-block and width: 100% for my-container. Fiddle

CSS

.my-container {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
width: 300px;
background-color: #3873fe;
margin: auto;
}

.my-container .margin {
    width: 100px;
    margin: 0 auto 50px;
    background-color: #00ff82;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    display: inline-block;
    width: 100%;
}
ajinkya narkar
  • 384
  • 1
  • 4