0

I have a .header div that is at the top of my page, and a .logo div inside of it. I want the logo div to have a top margin so there is some space between the top borders of header and logo, but when I add margin: 15px auto; to .logo, it behaves as if I put the margin style on .header. Here is some sample code:

html

<body>
    <div class="header">
        <div class="logo"></div>
    </div>
</body>

css

body {
    background-color: #CCC;
    margin: 0;
    padding: 0;
}

.header {
    height:80px;
    background-color: #8BB;
    margin: 0;
    /*padding: 15px 0 0;*/
    /*border: 1px solid yellow;*/
}

.logo {
    height: 30px;
    width: 500px;
    margin: 15px auto;
    background-color: #B5B;
    /*border: 1px solid red;*/
}

jsfiddle

I could get the desired results by using padding on .header instead, but I'm just curious what's going wrong with margins in my example? What's also weird is if you uncomment the border css I have in .header, it will work as expected.

Tested with FF and Chrome.

Nick Rolando
  • 25,879
  • 13
  • 79
  • 119

2 Answers2

2

Make sure the parent (header) has : overflow: hidden;

Elements with overflow set to anything other than visible (They do not collapse margins with their children.)

http://reference.sitepoint.com/css/collapsingmargins

Nick Rolando
  • 25,879
  • 13
  • 79
  • 119
Riskbreaker
  • 4,621
  • 1
  • 23
  • 31
  • Thanks. Why don't I have control over it without `overflow: hidden;`? – Nick Rolando Oct 08 '13 at 17:36
  • @Shredder check out the box model spec for CSS http://www.w3.org/TR/CSS2/box.html that should help you understand it. Also, here's the same question you posted: http://stackoverflow.com/questions/1762539/margin-on-child-element-moves-parent-element – disinfor Oct 08 '13 at 17:45
  • @disinfor Ahh... collapsing margins. Thanks you! – Nick Rolando Oct 08 '13 at 18:31
  • @Riskbreaker I edited your question with the reason why `overflow:hidden;` on parent works, with a reference. Hope you don't mind. – Nick Rolando Oct 08 '13 at 18:34
  • 1
    Of course not @Shredder Being more descriptive is all in favor to the user (Tron) :) – Riskbreaker Oct 08 '13 at 19:49
0

Add this CSS to .logo:

display: inline-block;

However this will align .logo to the left. You can fix it by adding text-align: center; to the .header

matewka
  • 9,912
  • 2
  • 32
  • 43