Giovanne Afonso
Giovanne Afonso

Reputation: 706

CSS margin not according parent

I have two divs, a "container" and a "content". If content is inside container, would fit container.

#container {
    display:block;
    width:300px;
    margin:auto;
    background:green;
}
#content {
    display:block;
    margin:20px; /* HERE IS THE ERROR */
    background:yellow;
}

The top and bottom margins are not inside parent, but left and right are.

Why does this happens?

EDIT: JSFIDDLE example:

Upvotes: 3

Views: 1770

Answers (2)

Adrift
Adrift

Reputation: 59799

This is due to margin collapsing - the top margins of a block level elements' first child (assuming it's also block level and participates in the normal flow) will always collapse with the top margin of its parent.

One way around this is to change the display value of the child div to inline-block.

#content {
    background: yellow;
    display: inline-block;
    margin: 20px;
}

Note: As AndyG pointed out you can also prevent margin collapsing by using padding or borders on the container div among many other ways. See the spec for a complete list.

Upvotes: 5

Belyash
Belyash

Reputation: 792

You can do next:

  • add overflow: hidden; to parent;
  • add border, like this border: 1px solid transparent; to parent
  • add padding to parent

    #container {
        background: green;
    
        border: 1px solid transparent;
    
        display: block;
        margin: auto;
        width: 300px;
    }
    #content {
        background: yellow;
        display: block;
        margin: 19px; /* because 1px for parent border */
    }
    

Example http://jsfiddle.net/3cXys/

Upvotes: 1

Related Questions