views:

820

answers:

5

I have a div with a <h1> tag in a div, with no margins. If I define any doctype, a white space appears above the div.

If I remove the <h1> tags, or remove the doctype definition, there is no space (as there should be. Why?

Example HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>
    <style>
        body{ margin:0 }
        #thediv{ background-color:green }
    </style>
</head>
<body>
    <div id="thediv">
        <h1>test</h1>
    </div>
</body>
</html>

The problem is the space above the green div, remove the DOCTYPE and the space disappears, change the <h1> tag to <b> and the space also disappears. It happens with any doctype (XHTML/HTML, strict/transitional/etc)

Happens in almost all browsers (Using http://browsershots.org). Amusingly, the only browser that seems to display it correctly was Internet Explorer 6.0..

+1  A: 

The DOCTYPE signals standards mode; this is why IE6 displays it "correctly" (actually wrong), because its standards support sucks. Basically, in standards mode it follows CSS layout rules as defined in the spec, as opposed to what you're expecting ("quirks mode").

Domenic
+3  A: 

It's likely something to do with "quirks" mode which some browsers invoke in the absence of a doctype (or the presence of a malformed one).

I'd suggest you reset your page's CSS and move on. Life's too short.

philistyne
That sorts it. I tried Yahoo's CSS-reset stylesheet, but it didn't sort this. The one you linked to does!
dbr
+6  A: 

The space above the green div is the correct behaviour according to the CSS spec. This is because the top margin of the h1 adjoins the top margin of the div.

One way to keep the margin of the h1 inside the div is to add a border to the div:

#thediv{ background-color:green; border: 1px transparent solid; }
Phil Ross
A: 

You have a couple of isssues here:

  1. Not having a DOCTYPE makes browsers use 'quirks mode' rather than interpreting your code in line with the standards. This is designed for old 'tag soup' code - if you are writing new code you should use a DOCTYPE and validate against it.

  2. Browsers are free to supply 'default styles' for HTML elements. If you want to make your page appear differently you have to specify how. Most pages at a minimum specify styles for the body and div elements. You also want to control the h1 element so you need to style that too.

domgblackwell