cdeszaq cdeszaq - 3 months ago 12x
HTML Question

Are self-closing tags valid in HTML5?

The W3C validator doesn't like self-closing tags (those that end with "

") on non void elements (those that may not ever contain any content). Are they still valid in HTML5?

Some examples of accepted void elements would be:

<br />
<img src="" />
<input type="text" name="username" />

Some examples of rejected non-void elements would be:

<div id="myDiv" />
<span id="mySpan" />
<textarea id="someTextMessage" />

Note: the W3C validator actually accepts void self-closing tags: the author originally had a problem because of a simple typo (
instead of
). However, self-closing tags are not 100% valid in HTML5 in general, and the answers elaborate on the issue of self-closing tags across various HTML flavors.


Not exactly

  • In HTML 4, <foo / means <foo> (which leads to <br /> meaning <br>&gt; and <title/hello/ meaning <title>hello</title>). Browsers did a very poor job of supporting this and the spec advises authors to avoid the syntax.

  • In XHTML, <foo /> means <foo></foo>, but since this only works in XML parsing mode and most documents are served as text/html there are compatibility guidelines to follow.

  • In HTML 5, the meaning of <foo /> depends on the type of element.

    • On HTML elements that are designated as void elements, it is allowed, but has no meaning. It is just syntactic sugar for people (and syntax highlighters) that are addicted to XML.
    • On other HTML elements, it is an error, but error recovery will cause browsers to treat it as a start tag. This will usually end up with a missing end tag putting subsequent elements as children of it.
    • Foreign elements (imported from XML applications such as SVG) treat it as self-closing syntax.