705

The W3C validator doesn't like self-closing tags (those that end with "/>") on non-void elements. (Void elements are those that may not ever contain any content.) Are they still valid in HTML5?

Some examples of accepted void elements:

<br />
<img src="" />
<input type="text" name="username" />

Some examples of rejected non-void elements:

<div id="myDiv" />
<span id="mySpan" />
<textarea id="someTextMessage" />

Note:
The W3C validator actually accepts void self-closing tags: the author originally had a problem because of a simple typo (\> instead of />); however, self-closing tags are not 100% valid in HTML5 in general, and the answers elaborate on the issue of self-closing tags across various HTML flavors.

Ardent Coder
  • 3,309
  • 9
  • 18
  • 39
cdeszaq
  • 29,170
  • 25
  • 111
  • 169
  • 2
    @Ben: oh, sorry, I think you're right. In this case, I misunderstood the original question, I thought the OP wants to know whether self-closing tags are valid at all in HTML5. But this means he just made typos in his code, or he didn't know how to appropriately write self-closing tags, which makes sense that W3C validator marked his code as invalid. – Sk8erPeter Dec 26 '12 at 17:16
  • 18
    To save time for future readers: yes, the syntax in the question is incorrect, and no, you should not change it. The OP has [explicitly and justifiably explained why](http://meta.stackexchange.com/a/165918/159231). Since it gave rise to the validation errors that prompted this question, the syntax should not be corrected. – Jordan Gray Apr 29 '13 at 14:57
  • @ikaruss I actually approved one of your suggested edits on this question at first (it seemed to make sense to me to remove irrelevant errors from both the question and its answers), but have just rolled them both back after reading the comment discussion here. Please read the comments above. Particularly notable is that in your edited form of the question, the claim that the W3C Validator didn't like the OP's code doesn't make sense any more. – Mark Amery Mar 22 '14 at 16:35
  • @mark-amery Ok. Though I oppose in this particular case... :) – ikaruss Mar 22 '14 at 16:43
  • 2
    Are you people *still* fighting over which direction the slashes should be facing? Come on. – BoltClock Apr 10 '14 at 01:32
  • 3
    @BoltClock Yup, still fighting. Guys: if this question was asking about `\>`, it should be closed as a useless fix-my-typo question. The answers all address `/>`. The `/>` version is the only useful one. Let it be. – Gilles 'SO- stop being evil' May 19 '14 at 23:01
  • 1
    Then the question has to be reworded, because the W3C validator actually accepts self-closing tags. It is hard to reword the question in such a way without compromising its integrity with respect to the original intent. Therefore, if we want to adhere to the rules of SO, we may have to sacrifice clarity in questions such as this one, even though it seems that editing the question is the only sensible thing to do, for the sake of the greater good on average. We could start another discussion on meta, if there are many other questions a similar issue. – Sergey Orshanskiy Nov 23 '15 at 05:25
  • Similar question: https://stackoverflow.com/questions/1946426/html-5-is-it-br-br-or-br – Anton Tarasenko May 26 '20 at 11:23

7 Answers7

1278
  • (Theoretically) in HTML 4, <foo / (yes, with no > at all) means <foo> (which leads to <br /> meaning <br>> (i.e. <br>&gt;) and <title/hello/ meaning <title>hello</title>). I use the term "theoretically" because this is an SGML rule that browsers did a very poor job of supporting. There was so little support (I only ever saw it work in emacs-w3m) that the spec advises authors to avoid the syntax.

  • In XHTML, <foo /> means <foo></foo>. This is an XML rule that applies to all XML documents. That said, XHTML is often served as text/html which (historically at least) gets processed by browsers using a different parser than documents served as application/xhtml+xml. The W3C provides compatibility guidelines to follow for XHTML as text/html. (Essentially: Only use self-closing tag syntax when the element is defined as EMPTY (and the end tag was forbidden in the HTML spec)).

  • In HTML5, the meaning of <foo /> depends on the type of element:

    • On HTML elements that are designated as void elements (essentially "An element that existed before HTML5 and which was forbidden to have any content"), end tags are simply forbidden. The slash at the end of the start tag is allowed, but has no meaning. It is just syntactic sugar for people (and syntax highlighters) that are addicted to XML.
    • On other HTML elements, the slash is an error, but error recovery will cause browsers to ignore it and treat the tag as a regular start tag. This will usually end up with a missing end tag causing subsequent elements to be children instead of siblings.
    • Foreign elements (imported from XML applications such as SVG) treat it as self-closing syntax.
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • 28
    "*... who are addicted to XML.*". You seem to suggest that XML compliance is bad. Yet, the end result in HTML5 seems to be that we still have to deal with angled brackets anyway (i.e. something with most of the inconveniences of XML), while it makes it harder to use XML-based tools (e.g. template tools or various processors). Even from a generation point of view, it would seem that `` and `` are not OK, while `` and `` are, which makes it harder for tool consistency. This looks like a lose-lose situation. – Bruno Oct 23 '14 at 15:48
  • 8
    @Bruno — HTML predates XML. The efforts to get people to move to XHTML failed. With `text/html`, browsers don't give any special meaning to the slash, so including it serves no practical purpose. It is only there to make it look more like XML for people who can't get out of the habit. – Quentin Oct 23 '14 at 15:51
  • 6
    @Quentin I don't entirely disagree. I just find it a bit of a shame that a valid XML equivalent isn't necessarily valid HTML5 (e.g. `` instead of `` or ``). Since HTML5 is effectively less stringent in general (possibly why XHTML failed), it could very well have tolerated something like ``. Unfortunately, it doesn't, so an XML-based template generator needs to know how to distinguish the production of void elements or self-closing elements: you can't even have one rule to say write all empty elements as ``. – Bruno Oct 23 '14 at 16:06
  • 4
    XHTML failed before HTML 5 was even on the horizon, and you can't have long form empty elements because browser error correction that predated XHTML would do things like treating `` as `
    ` so `
    ` would be a double line break. (and backwards compatibility with real world bad markup (like ``) is one of the design goals of HTML 5).
    – Quentin Oct 23 '14 at 16:11
  • 1
    FROM W3C: Void elements: area, base, br, col, embed, hr, img, input, keygen, link, meta, param, source, track, wbr "Void elements only have a start tag; end tags must not be specified for void elements." http://www.w3.org/TR/html5/syntax.html#void-elements – Fabio Nolasco Apr 28 '15 at 18:29
  • Do webcomponents (custom elements extending e.g. HTMLElement) fall into the "foreign elements" case or are there special rules for them? – Sebastian Barth Aug 12 '19 at 21:07
  • Found my answer here - Custom elements must not be used self-closing: https://stackoverflow.com/questions/23353419/how-to-create-a-self-closing-html5-tag-like-br – Sebastian Barth Aug 12 '19 at 21:11
  • 1
    Are there any actual disadvantages to using `
    `? Why wouldn't I want my HTML document to also be valid XML?
    – Aaron Franke Sep 02 '19 at 21:17
  • 1
    @Aaron Franke: Valid XHTML is much more than just
    . Most authors don't actually care about having 100% polyglot markup since they almost never need to serve application/xhtml+xml, they just care that their tags are self-closed and their attributes quoted, which doesn't serve anybody except themselves and anyone else working on the markup (readability, maintainability, for those not familiar with optional tags).
    – BoltClock Oct 02 '19 at 07:28
  • "On other HTML elements, the slash is an error, but error recovery will cause browsers to ignore it and treat the tag as a regular start tag. This will usually end up with a missing end tag causing subsequent elements to be children instead of siblings." ah so that's why I just lost 5 hours of my life dissecting my HTML and CSS down to their atoms to find a simple syntax problem that could've been called out in the console in two seconds... I'm going back to C (╯°□°)╯︵ ┻━┻ – CCJ Jul 05 '20 at 05:00
  • This is just a seriously good answer. – T.J. Crowder Mar 12 '21 at 08:04
417

As Nikita Skvortsov pointed out, a self-closing div will not validate. This is because a div is a normal element, not a void element.

According to the HTML5 spec, tags that cannot have any contents (known as void elements) can be self-closing*. This includes the following tags:

area, base, br, col, embed, hr, img, input, 
keygen, link, meta, param, source, track, wbr

The "/" is completely optional on the above tags, however, so <img/> is not different from <img>, but <img></img> is invalid.

*Note: foreign elements can also be self-closing, but I don't think that's in scope for this answer.

SherylHohman
  • 12,507
  • 16
  • 70
  • 78
Red Orca
  • 4,545
  • 1
  • 13
  • 12
  • 1
    IE10's Developer Tools is giving me "HTML1500: Tag cannot be self-closing. Use an explicit closing tag." on the line Any idea why that would be? – James in Indy Oct 14 '13 at 11:54
  • Ok, I found out that self closing tags should not have the slash (and removing it fixes my error). Cite: http://tiffanybbrown.com/2011/03/23/html5-does-not-allow-self-closing-tags/ – James in Indy Oct 14 '13 at 12:11
  • The spec has changed. Now, "void" or "self-closing" elements should *not* include the slash, when served as HTML 5 doctype. However, if it is being served as XHTML, the closing slash may be required (check the docs in this case). In practical use, pages will usually display as expected even if the closing `/` has been included, but this is not gauranteed (it is dependent on the browser effectively re-writing the code for you, and interpreting it as you intended.) Also, if for some reason your page is required to pass HTML 5 validation, it might not pass if you close tags for void elements. – SherylHohman Jan 28 '19 at 23:47
  • Regarding @SherylHohman's comment, I don't believe the spec has changed (or if it has, it has changed back). See https://www.w3.org/TR/html5/syntax.html#start-tags (8.1.2.1.6) - void (or foreign) elements may still include the slash. – ChrisC Feb 25 '19 at 10:43
64

In practice, using self-closing tags in HTML should work just like you'd expect. But if you are concerned about writing valid HTML5, you should understand how the use of such tags behaves within the two different two syntax forms you can use. HTML5 defines both an HTML syntax and an XHTML syntax, which are similar but not identical. Which one is used depends on the media type sent by the web server.

More than likely, your pages are being served as text/html, which follows the more lenient HTML syntax. In these cases, HTML5 allows certain start tags to have an optional / before it's terminating >. In these cases, the / is optional and ignored, so <hr> and <hr /> are identical. The HTML spec calls these "void elements", and gives a list of valid ones. Strictly speaking, the optional / is only valid within the start tags of these void elements; for example, <br /> and <hr /> are valid HTML5, but <p /> is not.

The HTML5 spec makes a clear distinction between what is correct for HTML authors and for web browser developers, with the second group being required to accept all kinds of invalid "legacy" syntax. In this case, it means that HTML5-compliant browsers will accept illegal self-closed tags, like <p />, and render them as you probably expect. But for an author, that page would not be valid HTML5. (More importantly, the DOM tree you get from using this kind of illegal syntax can be seriously screwed up; self-closed <span /> tags, for example, tend to mess things up a lot).

(In the unusual case that your server knows how to send XHTML files as an XML MIME type, the page needs to conform to the XHTML DTD and XML syntax. That means self-closing tags are required for those elements defined as such.)

Wand Maker
  • 17,377
  • 6
  • 43
  • 79
Michael Edenfield
  • 27,188
  • 4
  • 77
  • 114
  • 32
    will be treated as an opening tag, not a self-closed tag. That means the entire remainder of the document will be treated as being within the P element. That is not what I "probably expect", and will produce a serious mess on any non-trivial page. – mhsmith May 20 '13 at 17:09
  • "In practice, using self-closing tags in HTML should work just like you'd expect": `` is a good example of where it does not. Instead of an anchor, you'll get the following text turned into a link. For `` tag it is really important NOT to use self-closing syntax – Simon Kissane Apr 05 '21 at 00:11
15

HTML5 basically behaves as if the trailing slash is not there. There is no such thing as a self-closing tag in HTML5 syntax.

  • Self-closing tags on non-void elements like <p/>, <div/> will not work at all. The trailing slash will be ignored, and these will be treated as opening tags. This is likely to lead to nesting problems.

    This is true regardless of whether there is whitespace in front of the slash: <p /> and <div /> also won't work for the same reason.

  • Self-closing tags on void elements like <br/> or <img src="" alt=""/> will work, but only because the trailing slash is ignored, and in this case that happens to result in the correct behaviour.

The result is, anything that worked in your old "XHTML 1.0 served as text/html" will continue to work as it did before: trailing slashes on non-void tags were not accepted there either whereas the trailing slash on void elements worked.

One more note: it is possible to represent an HTML5 document as XML, and this is sometimes dubbed "XHTML 5.0". In this case the rules of XML apply and self-closing tags will always be handled. It would always need to be served with an XML mime type.

Community
  • 1
  • 1
thomasrutter
  • 104,920
  • 24
  • 137
  • 160
6

Self-closing tags are valid in HTML5, but not required.

<br> and <br /> are both fine.

Nick
  • 1,814
  • 1
  • 18
  • 37
  • 12
    According to HTML5 spec, self-closing syntax (`/>`) can't be used on a non-void HTML element. – naXa Jul 30 '15 at 12:20
  • 3
    The question was about self-closing tags on **non-void elements**, like `

    ` or `
    `.
    – thomasrutter Jun 28 '16 at 06:06
  • 2
    Initially the question was not specifically about non-void elements. It was more like, can you still use `<...>` as in XHTML or do you have to remove the `/` in HTML5. The question was changed multiple times after. – Nick Sep 20 '17 at 08:37
  • Either way, the answer is that the slash will be ignored, which will break elements not declared as void, but will be compatible with void elements. – thomasrutter Jul 10 '19 at 01:31
5

I would be very careful with self closing tags as this example demonstrates:

var a = '<span/><span/>';
var d = document.createElement('div');
d.innerHTML = a
console.log(d.innerHTML) // "<span><span></span></span>"

My gut feeling would have been <span></span><span></span> instead

Andreas Herd
  • 580
  • 5
  • 10
  • 2
    This is described in the accepted answer: `On other [than void] HTML elements, the slash is an error, but error recovery will cause browsers to ignore it and treat the tag as a regular start tag. This will usually end up with a missing end tag causing subsequent elements to be children instead of siblings.` – Palec May 20 '17 at 19:40
1

However -just for the record- this is invalid:

<address class="vcard">
  <svg viewBox="0 0 800 400">
    <rect width="800" height="400" fill="#000">
  </svg>
</address>

And a slash here would make it valid again:

    <rect width="800" height="400" fill="#000"/>
Leo
  • 2,274
  • 2
  • 17
  • 16