26 Jul 2007

Self-closing tags?

Tags: ,

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?

Self-closing tags demo

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.

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

2 Responses to “Self-closing tags?”

  1. Tadej / Jul 26, 2007 9:17 pm

    This code produces quite nice graphic in FF 2.0.0.5 :)

  2. IIMarckus / Mar 31, 2009 5:01 am

    The reason for this is that you are serving the page with an HTML media type, not an XML one. Try renaming the file to tags.xht and you will see that it works correctly—but Internet Explorer will not load the page at all.

Leave a Reply