CSS margin terror; Margin adds space outside parent element [duplicate]

Add overflow:auto to your #page div.

jsFiddle example

And check out collapsing margins while you're at it.


Add any one of the following rules:

float: left/right;
position: absolute;
display: inline-block;
overflow: auto/scroll/hidden;
clear: left/right/both;

This is caused by collapsing margins. See an article about this behavior here.

According to the article:

The W3C specification defines collapsing margins as follows:

“In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding, or border areas, or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.”

This is also true for parent-child elements.

All the answers include one of the possible solutions:

There are other situations where elements do not have their margins collapsed:

  • floated elements
  • absolutely positioned elements
  • inline-block elements
  • elements with overflow set to anything other than visible (They do not collapse margins with their children.)
  • cleared elements (They do not collapse their top margins with their parent block’s bottom margin.)
  • the root element

Problem was the parent not taking into account children for height. Adding display:inline-block; did it for me.

Full CSS

#page {
    margin:0;
    background:#FF9;
    display:inline-block;
    width:100%;
}

See Fiddle


Just add border-top: 1px solid transparent; to your #page element.

From w3.org

Two margins are adjoining if and only if:
- no line boxes, no clearance, no padding and no border separate them


Add the following rule:

overflow: hidden;

This is caused by collapsing margins. See an article about this behavior here.

According to the article:

If a parent element does not have any top padding or less top margin then its first child, then elements are rendered in a way that makes the parent element appear to have the child element's margin. So this can happen anywhere on a page where these conditions are met, but it tends to be most obvious at the top of a page.