Self-Closing and End Tags in XHTML and HTML

Correct markup for end tags in XHTML and HTML can get confusing real quick because of all the exceptions and lack of enforcement, as others have pointed out. Wrong markup, such as using XHTML’s self-closing tags, is often corrected by browsers or ignored, as this comment explains. As a concise general statment: XHTML requires end tags and allows any tag to be self-closed, but HTML’s end tags are absent with void elements, optional with some elements, and are sometimes allowed to be self-closing.

A void element is one that cannot have any content. These include area, base, br, col, command, embed, hr, img, input, keygen, link, meta, param, source, track, and wbr elements. These elements will never have closing tags. However, they are allowed to be self-closing because the “/” is just ignored. Thus, technically, both of the following are correct:

<img src="myimg.png">
<img src="myimg.png" />

With some elements end tags can be ommitted by W3C specification. In fact, even some start tags like html can be ommitted, but we’ll set that aside. The cases for when ommitting end tags is allowed are many, but when trying to minimalize the size of the document being transferred it may be of benefit. Unless document size is an extreme issue, the general case is to always include end tags for non-void elements.

In HTML, only void and foreign elements can be self-closing, as W3C specifies (see #6). Void elements have been mentioned already, and foreign elements just include those from the MathML and SVG namespaces. In XHTML, all elements must be closed, so unless there is content in the element perhaps it’s best to use the self-closing method because it is condensed and elegant. Yet, with HTML it is like the case of omitting end tags, using self-closing tags should be avoided.

To conclude, here are the differences:

XHTML

  • Always use end tags, they are required
  • Use self-closing tags with empty elements for simplicity and elegance

HTML

  • Always use end tags (except on void and foreign elements), even though there are cases when they are not required
  • Never use self-closing tags, because even though they can be used on void and foreign elements, closing the element isn’t needed
Published
Categorized as XML

By Joe Purcell

Joe Purcell is a technology virtuoso, cyberspace frontiersman, and connoisseur of Linux, Mac, and Windows alike.

Leave a comment