Nrc
Nrc

Reputation: 9787

The margin of a div respect its parent

I am confused about the margins. I have a logo inside a div content. If I give a margin-top to the div logo this margin appears between the content and the page. Why?

Here is the example: http://jsfiddle.net/bCkpb/

CSS:

#content {
    position:relative;
    margin:0 auto;
    width:300px; height:250px;
    background-color:blue;
}

#logo {
    margin:20px auto; /* Why this 20px appear between the page and the content? */
    width:120px; height:120px;
    background:yellow;
}

HTML:

<div id="content">
    <div id="logo"> </div> 
</div>

Upvotes: 1

Views: 1193

Answers (1)

Adrift
Adrift

Reputation: 59799

It's because the top-margin of a block-level element and the top-margin of its first block-level child will always collapse (unless any border, padding, line boxes or clearance separate them). One way to prevent this behaviour is to add an overflow value other than visible to the #content div. You can also change the display value of #content to inline-block.

http://jsfiddle.net/bCkpb/3/

Upvotes: 1

Related Questions