Why is the <img> tag not closed in HTML?

HtmlImageXhtml

Html Problem Overview


For curiosities sake, why is the <img> tag not closed in HTML?

<img src="smiley.gif" alt="Smiley face" height="42" width="42">

I also noticed that <img> tags are explicitly closed in XHTML...

<img src="smiley.gif" alt="Smiley face" height="42" width="42"/>

W3Schools: Image Tag

Html Solutions


Solution 1 - Html

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 - Html

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 - Html

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.

Solution 4 - Html

<img> tag is basically a Void element.

For your understanding:

The image does not have any content. Image tag will just give the path from where the resource will be loaded through src attribute. So, it does not require any end element.

Whereas <img src="smiley.gif" alt="Smiley face" height="42" width="42"/>, this code is for XHTML version.

Solution 5 - Html

You won't put anything in the image like in h1 you would put text but in image you won't put anything on it.

Example:

<h1>hi</h1>
<img src=blblb alt=blbl/>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionѺȐeallүView Question on Stackoverflow
Solution 1 - HtmlQuentinView Answer on Stackoverflow
Solution 2 - HtmlkmoeView Answer on Stackoverflow
Solution 3 - HtmlJosh Davenport-SmithView Answer on Stackoverflow
Solution 4 - HtmlAzeezView Answer on Stackoverflow
Solution 5 - HtmlSurView Answer on Stackoverflow