Strange problem with borders and margins

Hello, folks. I am starting a new site…JUST starting a new site…and have encountered a problem I’ve not seen before. I am pretty new to CSS, so I guess that isn’t a surprise though.

Basically…I am getting a top margin on my page of exactly 21px regardless of what I have my body and header tags set to.

My HTML looks like such:


<body>
	  <div id="header">
		  <h1 class="logo"><a href="/" title="Hello There">Why Hello!</a></h1>
	  </div>
</body>

And my CSS looks like such:


body {
	background: #fff url(../images/background.png) repeat;
	color: #333;
	margin:0;
	padding:0;
	text-align: left;
}
#header {
	margin:0;
	padding:0;
}

That’s it. Pretty simple. Yet it is still inserting a margin at the top of my page of 21 pixels. I can remove this margin, I found by accident, by changing the CSS structure of my #header element to read as:


#header {
        border: 1px solid #000;
	margin:0;
	padding:0;
}

So basically…if I give the header a border, I remove its top margin. I am so confused as to why that happens.

Please help!

Hi, this is known as margin collapse. A child of #header must have a top margin set (maybe a <ul>) and as a result the margin is pushing through the #header and to the <body> pushing it down. A border/padding fixes this as you noticed.
Read margin collapse
http://www.w3.org/TR/CSS21/box.html

Here’s an article which my help get your head around collapsing margins too:

Thank you guys! Not only did I fix it, but I have a better understanding of WHY it happened.

Ya’ll rock.

You’re welcome :).