Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why <div class="clear"></div> instead of <div class="clear"/>?

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;
}
like image 806
Edward Tanguay Avatar asked Oct 30 '10 17:10

Edward Tanguay


1 Answers

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

like image 80
bobince Avatar answered Sep 27 '22 15:09

bobince