views:

99

answers:

2

I just realized that:

<div class="clear"/>

after a series of floating divs causes layout havoc, while

<div class="clear"></div> 

works fine.

Can anyone explain this?

This is the CSS:

div.clear {
    clear:both;
}
+8  A: 

According to the HTML 4.01 spec, Section 7.5.4, the <div> tag requires a closing tag.

Donut
+12  A: 
<div class="clear"/>

If you are serving an XHTML page as text/html, browsers aren't reading it using a real XML parser. They're using a plain old HTML parser which doesn't know about self-closing tags. To an HTML4 parser, that's just an open tag with some weird punctuation in it. (If browser parsers really used the rules of SGML, it would be some other undesirable thing completely, but they don't.)

Until IE9 becomes widespread, we won't be able to serve general-purpose web pages as application/xhtml+xml, which is what's required to make the browser use real XML parsing rules. Until that time, if you write XHTML documents you will need to make your documents also backwards-compatible with plain HTML, which means always and only using self-closing syntax on elements that are declared to have an EMPTY content model. (img, br, etc.)

There are more rules about what you have to do to write HTML-compatible XHTML, but that's the most important one. Appendix C of the XHTML 1.0 standard is a list of the differences; it looks a bit complicated, but many of the points address features you don't want to be using anyway, and some are now irrelevant as they're talking about being ancient browsers like Netscape 4. The practice of putting a space before /> is no longer required by anything in common use, for example.

bobince
"Until IE ${whatever} I'll be 100 years old"
cherouvim
The behavior will probably also change if you put a DOCTYPE at the head of your page.
Ben Jackson
DOCTYPE doesn't affect the parser mode; even with a propert XHTML doctype, the browser will still use the traditional HTML parser if the document is served as `text/html`. Of course not having a doctype and thereby being in Quirks Mode can indeed mess up a number of *other* behaviours to do with CSS floats thanks to its emulation of IE5-era bugs...
bobince