Why is the <img> tag not closed in HTML?
Solution 1:
Historically, HTML has been based on SGML which allows tags to be omitted under certain conditions.
Since the <img>
element cannot have any child nodes, it is defined as EMPTY and the end tag is forbidden (as it would serve no purpose).
XHTML is HTML expressed in XML, and XML does not support optional or forbidden tags (although it allows a self-closing tag to substitute for a start+end tag pair), so it has to be explicitly closed there.
HTML 5 is backwards compatible with versions of HTML that were SGML based.
Solution 2:
The <img>
tag represents what is known as a void element (see HTML5 spec), so called because it can't have any contents (unlike, say <a>
or <div>
). Therefore there is no syntactic reason why it should need to be closed in HTML.
XHTML, however, is based on XML, where every tag needs to be closed.
Solution 3:
It is what is called a void element which just means the element must not have any content (but can have attributes.) The HTML5 spec has this to say about void elements:
if the element is one of the void elements, or if the element is a foreign element, then there may be a single "/" (U+002F) character. This character has no effect on void elements
So there's no real reason to have the single "/" (U+002F) character, but it won't break anything if it's included.