0

My centered header bottom margin is overflowing the parent container, causing a gap between yellow and orange wrappers:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Document</title>
    <style>
    .header-wrap{
      background-color:yellow;
    }
    .content-wrap{
      background-color:orange;
    }
    .header{
      margin:0 auto 1em auto;
      background-color: red;
      width:40em;
    }
  </style>
</head>
<body>
  <div class="header-wrap">
    <div class="header">header</div>
  </div>
  <div class="content-wrap">
    <div class="content">content</div>
  </div>
</body>
</html>

If I use a simple clearfix for parent .header-wrap{overflow:hidden;} the problem is fixed, but I don't understand why I need to use a clearfix here, since I'm not using floating elements at all.

From what I know, the clearfix is applied on the parent to clear any floated children inside, which is not the case here.

Can anyone explain why is this happening?

Marius
  • 43
  • 7
  • Just to be very clear: I want the header centered and I want that bottom margin on it, it's intended to be there, I just don't understand why that margin overflows the parent, since it's not floated. You can see the problem here: http://jsfiddle.net/bJ2e5/2/ – Marius Apr 16 '14 at 08:38
  • Check out this question: http://stackoverflow.com/questions/2176520/why-would-margin-not-be-contained-by-parent-element – George Apr 16 '14 at 08:41

2 Answers2

0
.header{
      margin:0 auto 1em auto; //margin 1em at bottom
      background-color: red;
      width:40em;
}

change it to

.header{
      margin:0 auto;
      background-color: red;
      width:40em;
}

DEMO

4dgaurav
  • 11,360
  • 4
  • 32
  • 59
  • The whole point of the question is that I want that bottom margin there but I don't understand why it overflows the parent. – Marius Apr 16 '14 at 08:31
0

Add float:left or inline-block to your header. Currently in your structure you mentioned the margin-bottom to header div which is inside the header-wrap class. header is the child element. To display yellow background, you must need to wrap the child element.

DEMO

CSS

.header-wrap {
    background-color: #FFFF00;
    display: inline-block; 
}
Santy
  • 304
  • 1
  • 3