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.

4

2 回答 2

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

于 2013-10-08T17:17:39.563 回答
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

于 2013-10-08T17:17:43.247 回答