skip to Main Content

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


  1. 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.

    Login or Signup to reply.
    • XHTML requires that all elements be explicitly ended (e.g. </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.
    • HTML forbids end tags on <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.
    • People also make mistakes
    Login or Signup to reply.
  2. 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:

    <img src="example.jpg">
    

    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, and height. In these cases, the img 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 an img tag with additional attributes and a closing tag:

    <img src="example.jpg" alt="Example Image" width="500" height="300">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search