CSS margin terror; Margin adds space outside parent element

jamietelin picture jamietelin · Nov 26, 2012 · Viewed 84.4k times · Source

My css margins doesn't behave the way I want or expect them to. I seems like my header margin-top affect the div-tags surrounding it.

This is what I want and expect: What I want....

...but this is what I end up with: What I get...

Source:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Margin test</title>

<style type="text/css">
body {
    margin:0;
}
#page {
    margin:0;
    background:#FF9;
}
#page_container {
    margin:0 20px;
}
h1 {
    margin:50px 0 0 0;
}
</style>

</head>

<body>

<div id="page">
    <div id="page_container">
        <header id="branding" role="banner">
            <hgroup>
                <h1 id="site-title"><span><a href="#" title="Title" rel="home">Title</a></span></h1>
                <h2 id="site-description">Description</h2>
            </hgroup>
        </header>
    </div>
</div>

I have exaggerated the margin in this example. Default browser margin on h1-tag is somewhat smaller, and in my case I use Twitter Bootstrap, with Normalizer.css which sets default margin to 10px. Not that important, main point is; I can not, should not, want not change the margin on the h1-tag.

I guess it is similar to my other question; Why does this CSS margin-top style not work?. Question is how do I solve this specific issue?

I have read a few threads on similar problems, but haven't found any real answers and solutions. I know adding padding:1px; or border:1px; solves the problem. But that only adds new problems, since I do not want a padding nor a border on my div-tags.

There must be a better, best practice, solution? This must be pretty common.

Answer

j08691 picture j08691 · Nov 26, 2012

Add overflow:auto to your #page div.

jsFiddle example

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