0

Please look at the following example: https://jsfiddle.net/9wbm179c/

The margin-top:50px; is making this ugly gap between body and .outter. Just read the code and this message again: between body and .outter... Isn't it should be making the gap between .inner and .outter?

html,
body {
  padding: 0;
  margin: 0;
}

body {
  background: #777;
}

.outter {
  background: #099;
  text-align: center;
}

.inner {
  background: #ff0;
  width: 400px;
  height: 150px;
  margin: 0 auto;
  margin-top: 50px;
}
<div class="outter">
  <div class="inner">

  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
laudbob
  • 47
  • 1
  • 6
  • Possible duplicate of [Margin-Top push outer div down](http://stackoverflow.com/questions/2680478/margin-top-push-outer-div-down) – t.niese Apr 02 '17 at 16:21
  • Can you please elaborate your issue? What i can see is difference between outter and inner is because of inner is having margin:0 auto; Please clarify your question. – Mayank Nimje Apr 02 '17 at 16:22
  • [How to disable margin-collapsing?](http://stackoverflow.com/questions/19718634/how-to-disable-margin-collapsing) – t.niese Apr 02 '17 at 16:22
  • thanks folks! I was goin nuts – laudbob Apr 02 '17 at 16:31

1 Answers1

0

What you're seeing is called "margin collapse." https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

Parent and first/last child - If there is no border, padding, inline content, block_formatting_context created or clearance to separate the margin-top of a block from the margin-top of its first child block, or 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.

You can address it a number of ways. One way is by using overflow:hidden; on the parent element .outter. You could also use padding-top: 50px on .outter instead of margin-top on .inner

html,body {
  padding:0;
  margin:0;
}
body {
  background:#777;
}
.outter {
  background:#099;
  text-align:center;
  overflow: hidden;
}
.inner {
  background:#ff0;
  width:400px;
  height:150px;
  margin:0 auto;
  margin-top:50px;
}
<div class="outter">
  <div class="inner">
    
  </div>
</div>
Michael Coker
  • 52,626
  • 5
  • 64
  • 64