I want the div to go the top of the page, in firefox I have to use a negative margin, but then in other browsers it takes the div past the top of the page. ive posted the code. what can i do?



<title>B and C instuments</title>
<link rel="stylesheet" type="text/css" href="bandc.css">


<div id="header">
<h1>B and C</h1>

<div id="navigation">
<a href="">Home</a>
<a href="">About</a>
<a href="">Contact</a>
<a href="">Form</a>

<h2> B and C instruments</h2>
<p id="welcome">Looking for a machine shop that will create high  quality parts that you can rely on? Well B and C can satisfy your needs
 just like we've satisfied every other clients need for 40+ years.</p>

<a id="learnmore" href="">Learn more</a>



background-color: #CFECEC;
margin: 0;
padding: 0;

background-color: white;
width: 100%;
height: 100px;

background-color:  red;
width: 100%;
height: 50px;
  • the "just like we've satisfied every other clients need for 40+ years." is part of the paragraph with the id of welcome canyonchase1 over 9 years ago
  • Fixed the markup for you. o.k.w over 9 years ago

2 answers

o.k.w 2355
This was chosen as the best answer

The gap is caused by the <h1> tag which somehow introduce it's default margin of 21px out of the div. This is due to the effect of uncollapsing margin for empty content/padding or border areas (Refer to the w3c box model).

Here's a hack around it by using padding to replace the top margin:

#header h1 {
    margin-top: 0;
    padding-top: 21px; /* or set to any value you desire */

Another way is to introduce a 1px border (with the same DIV background-color) to the DIV and compensating it with the width and/or height of the DIV.

Answered over 9 years ago by o.k.w
  • Perfect. I've always wondered why it's done that and I never knew how to fix it. It worked perfectly. Mega thanks. canyonchase1 over 9 years ago

using top: 21px;, left, right, bottom is a lot more cross browser friendly

Answered over 9 years ago by kwek-kwek