Void (empty) elements and self-closing start tags in HTML

The syntax for void elements and self-closing tags is something most web authors get right. However, there are two types of mistakes that I see every now and then: using end tags on void elements and using self-closing start tags on elements that can have content.

End tags on void elements

Most HTML elements have a start tag and an end tag that indicate where the element begins and where it ends. There is a group of elements that are exceptions to this rule. These elements are called empty or void and only have a start tag since they can't have any content. They must not have an end tag in HTML.

The void elements in HTML 4.01/XHTML 1.0 Strict are area, base, br, col, hr, img, input, link, meta, and param. HTML5 currently adds command, keygen, and source to that list.

To create a button with the input element, do this if you use an XHTML doctype:

  1. <input type="submit" value="Ok" />

And this if you use HTML:

  1. <input type="submit" value="Ok">

Both are ok if you use HTML5.

Do not do this:

  1. <input type="submit" value="Ok"></input> <!-- Bad! -->

Self-closing start tags on elements that can have content

The opposite problem is when an element that can have content is empty. If it is not a void element it must still have an end tag.

To create a named anchor with no content, do this:

  1. <a id="myanchor"></a>

Do not do this:

  1. <a id="myanchor" /> <!-- Bad! -->

To load a JavaScript file, do this:

  1. <script type="text/javascript" src="script.js"></script>

Do not do this:

  1. <script type="text/javascript" src="script.js" /> <!-- Bad! -->

Notes and further reading

I should note that both end tags for void elements and minimised syntax on empty elements that can have content are allowed in XHTML documents served with an XML content-type (application/xhtml+xml). However, since that makes those documents incompatible with HTML I would recommend that people using real XHTML stick to the syntax that works in both flavours.

See the following documents for more details:

This post is a Quick Tip. Background info is available in Quick Tips for web developers and web designers.

Posted on May 20, 2010 in Quick Tips, HTML 5, (X)HTML