The W3C validator (Wikipedia) does not like the use of self-closing tags (tags ending in "/>
") on non-empty elements. (Empty elements are those that never contain any content.) Are they still valid in HTML5?
Some examples of accepted empty elements:
Some examples of rejected non-empty elements:
Note:
The W3C validator actually accepts empty self-closing tags: the author initially encountered the problem because of a simple typo (using >
instead of />
;); However, self-closing tags are not fully valid in HTML5, and the answer elaborates on the issue of self-closing tags in different HTML versions.
Self-closing divs will not be validated. This is because div is anormal element, not anempty element.
According to theHTML5 specification, tags that cannot contain any content (calledempty elements) can be self-closing*. This includes the following tags:
The "/" on the above tag is completely optional, so
is no different from
, but
is invalid.
*Note:External elementscan also be self-closing, but I think that's outside the scope of this answer.
Theoretically, inHTML 4,(yes, without anymeans
>
) means
(which results in
meaning
(i.e.>
) and>
hello
). I use the term "theoretically" because this is aSGMLrule that browsers support very poorly. Support is so sparse (I've only seen it work inemacs-w3m) that thespecification advises authors to avoid using this syntax.InXHTML,
means
. This is theXMLrule that applies to all XML documents. That said, XHTML is typically served astext/html
, which (at least historically) is used by browsers using a different parser than documents served asapplication/xhtml xml
deal with. The W3C providescompatibility guidelines
for XHTML astext/html. (Basically: use self-closing tag syntax only if the element is defined as EMPTY (and closing tags are prohibited in the HTML specification)).InHTML5, the meaning of
depends on the type of element:For elements that are designated as- empty(basically "elements that existed before HTML5 and were prohibited from containing any content"), closing tags are prohibited. A slash at the end of the opening tag is allowed but has no meaning. This is just syntactic sugar for people who are used to XML (and syntax highlighters).
As with other HTML elements, the slash is
- an error, but error recovery will cause the browser to ignore it and treat the tag as a regular opening tag. This often results in missing closing tags, making subsequent elements child elements rather than siblings.
External elements (imported from XML applications such as SVG) are treated as self-closing syntax.