For better understanding, I split this post into three parts. The first one may be skipped by experienced web developers.
Some basic XHTML tag-closing theory
In HTML, tags needn’t be closed. So this is correct:
<ul> <li>Item 1 <li>Item 2 </ul>
But with XHTML, we have to respect the strict XML standards, meaning each and every tag has to be closed. A bit more code is needed.
<ul> <li>Item 1</li> <li>Item 2</li> </ul>
Also, we have to take care of tags with no closing tag, such as <br>:
<br> is wrong, while
<br /> is correct.
This way XML parsers can read our HTML code. And what’s more, the code is much easier to read and understand by human beings, such as ourselves. If done correctly it doesn’t affect the way our code is rendered.
Can every tag be self-closing?
According to W3, every tag can be self-closing, therefore
<div /> is a valid piece of XHTML code. But can we use this in the real world?
As you can see in the demo, browsers get confused by self-closing tags. They treat them as if we never closed them. You can try navigating the HTML structure with the Firebug extension for Firefox, to see how confused they really get.
I’ve tested this with IE7, Opera 9.2, Safari 3, Firefox 2 and Konqueror 3.9. All produced the same results.
Do self-close tags with no closing tag, such as br, hr, img, link, base or meta. For example,
<br></br> is not valid. But don’t do it to tags that do not expect that. It may be valid, but you won’t like the result. Just do
<a name="anchor"></a> or such.