Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS margin not according parent

Tags:

css

margin

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:

like image 335
Giovanne Afonso Avatar asked Dec 09 '25 10:12

Giovanne Afonso


2 Answers

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.

like image 128
Adrift Avatar answered Dec 12 '25 05:12

Adrift


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/

like image 33
Belyash Avatar answered Dec 12 '25 06:12

Belyash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!