Coder Perfect

How do you properly close the image> tag?

Problem

<img src='stackoverflow.png'>
<img src='stackoverflow.png'></img>
<img src='stackoverflow.png' />

Which one(s) is/are the proper one(s)?

Asked by insertusernamehere

Solution #1

This one is genuine HTML5 and can be used without being closed. It’s what’s known as a void element:

<img src='stackoverflow.png'>

The following are valid XHTML tags. They have to be closed. The later one is also fine in HTML 5:

<img src='stackoverflow.png'></img>
<img src='stackoverflow.png' />

Answered by Marvin Rabe

Solution #2

<img src='stackoverflow.png' />

Works fine and closes the tag properly. Best to add the alt attribute for people that are visually impaired.

Answered by Ed Heal

Solution #3

In HTML5, only the first one is correct.

<img src='stackoverflow.png'>  

In XHTM, only the last two are valid.

<img src='stackoverflow.png'></img>  
<img src='stackoverflow.png' />

(An alt attribute should _usually_ be included, even if it isn’t strictly needed.)

However, your HTML5 page will most likely display as intended because browsers will rewrite or interpret your html to reflect what you intended. This could suggest that it changes a tag from div /> to div>/div>. Maybe it merely ignores the slash at the end of img… />. For legacy validation, see 2016: Serve HTML5 as XHTML 5.0. 2011 conversation and further links can be found here, though some details may have changed since then.

This is partly due to browsers’ valiant efforts to repair errors. Also, there is a lot of misunderstanding about self-closing tags and void tags. Finally, the specification has changed or is not always clear, and browsers attempt to be backwards compatible.

While any of the three solutions will generally suffice, only the first complies to the HTML5 standard and is guaranteed to pass an HTML5 validator.

It might be a good idea to:

The following is a list of HTML5 tags that should not be closed:

 <br>    <hr>    <input>       
 <img>  <link>   <source>  
 <col>  <area>   <base>
 <meta> <embed>  <param>  
<track>  <wbr>   <keygen> (HTML 5.2 Draft removed)

Answered by SherylHohman

Solution #4

Both are correct answers. HTML5 follows tight regulations, and we can close all tags in HTML5. As a result, it is up to you to decide whether to utilize HTML5 or HTML and provide an acceptable response.

<img src='stackoverflow.png'>
<img src='stackoverflow.png' />

The second characteristic is more suitable.

Answered by PLB

Solution #5

You should utilize the following tags to make the best use of tags:

<img src="" alt=""/>

You can also use the following in HTML5:

<img src="" alt="">

Both of them are HTML5-compliant. Choose one of them and stick to it.

Answered by Md. A. Barik

Post is based on https://stackoverflow.com/questions/14860492/how-to-close-img-tag-properly