Do I need a "/" at the end of an <img> or <br> tag, etc.? [duplicate]
Do you need to have a /
at the end of an img
tag? I saw an example on W3schools.com without a /
:
<img src="smiley.gif" alt="Smiley face" height="42" width="42">
I know it isn't necessary to self-close the tag, at least in my browser, but should I do so?
The /
is only required for XHTML & XML.
If you're using a HTML5 doctype, then there's no need to terminate self-closing tags in this way.
This applies to <img src="img.png" />
, <br />
, <hr />
etc.
I.e. Just use <img src="img.png">
, <br>
and <hr>
.
If you need an empty element (like a div
), don't use <div />
, instead use <div></div>
. This is important since in HTML5, the slash is ignored and <div />
is interpreted as <div>
without a closing tag.
It's only required for XHTML standards, as mentioned in other answers. HOWEVER, it also has another use.
Some code editors such as Notepad++ allow you to expand/collapse tags to make for faster viewing. But if you just put <img>
, how is it supposed to know the difference between a tag that doesn't require an end tag, and one that uses the same tag name but does (ie. in XML)? This is especially true if you use custom tags.
Therefore, using />
explicitly tells the editor that it's self-closing, allowing it to continue working just fine and not having it warn you about a mismatched tag.
Apart from the validity issue, which simply depends on the doctype you are validating against, the slash really matters only if your page is served with an XML content type, such as application/xhtml+xml
(which is rarely used, because old versions of IE choke on it).
If you do that, then well-formedness error handling is Draconian: any error (such as a start tag without a matching end tag, which can be the start tag itself when the <img ... />
syntax is used) prevents the page from being displayed at all, and instead an error message is shown.