I read in tutorials that img
tags don’t have ending tag. But, while inspecting html of various pages I noticed that some img
tags have ending tag </img>
or <img ... />
and some don’t have ending tag and appear just <img ... >
. In what cases they don’t have an ending tag?
3
Answers
The syntax
<img ... />
on a ‘self-closing tag’ is valid in HTML, but not required.It was required in the stricter XHTML, a markup language similar to HTML, to signify that a tag was self-closing. XHTML has largely lost out in popularity to HTML due to the latter being more lenient and more widely supported.
Because a lot of developers learned and used XHTML, many still use the self closing tag syntax despite it not being required.
<img ...>
is the recommended usage.As an interesting side note, this syntax is now used again in React/JSX components.
</img>
) but provides alternative syntax with a/
at the end of the start tag (instead of an end tag) for elements which have no content.<img>
elements but (for backwards compatibility with XHTML) permits a meaningless/
to appear at the end of a start tag on elements where the end tag is forbidden.In HTML, the img tag is what’s known as a "void element". Void elements are elements that don’t have any content or nested elements. As a result, they don’t require a closing tag.
For example, the following
img
tag is perfectly valid:This is because there is no content or nested elements within the
img
tag, so it doesn’t require a closing tag.However, some img tags may include additional attributes, such as
alt
,width
, andheight
. In these cases, theimg
tag still doesn’t require a closing tag, but some people prefer to include it anyway for consistency and readability purposes. Here’s an example of animg
tag with additional attributes and a closing tag: