Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a h1 tag display different in a div, when a doctype is set?

Tags:

html

css

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">
<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..

like image 457
dbr Avatar asked Dec 23 '22 14:12

dbr


1 Answers

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; }
like image 165
Phil Ross Avatar answered Jan 17 '23 18:01

Phil Ross