Are (non-void) self-closing tags valid in HTML5?
Asked Answered
D

8

771

The W3C validator (Wikipedia) 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.
Dulciana answered 24/8, 2010 at 15:28 Comment(8)
@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.Fiesole
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. Since it gave rise to the validation errors that prompted this question, the syntax should not be corrected.Metro
@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.Obviate
@mark-amery Ok. Though I oppose in this particular case... :)Nuke
Are you people still fighting over which direction the slashes should be facing? Come on.Blue
@Blue 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.Symphony
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.Kattiekatuscha
Similar question: https://mcmap.net/q/36827/-html-5-is-it-lt-br-gt-lt-br-gt-or-lt-br-gtAnders
E
1341
  • (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.
Eulau answered 24/8, 2010 at 15:37 Comment(10)
"... 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 <object data="..." /> and <img src="..."></src> are not OK, while <object data="..."></object> and <img src="..." /> are, which makes it harder for tool consistency. This looks like a lose-lose situation.Inedited
@Inedited — 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.Eulau
@Eulau 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. <img ...></img> instead of <img ...> or <img ... />). Since HTML5 is effectively less stringent in general (possibly why XHTML failed), it could very well have tolerated something like <img ...></img>. 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 <tag></tag>.Inedited
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 </br> as <br> so <br></br> would be a double line break. (and backwards compatibility with real world bad markup (like </br>) is one of the design goals of HTML 5).Eulau
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." w3.org/TR/html5/syntax.html#void-elementsThistle
Do webcomponents (custom elements extending e.g. HTMLElement) fall into the "foreign elements" case or are there special rules for them?Featherbedding
Found my answer here - Custom elements must not be used self-closing: #23353919Featherbedding
Are there any actual disadvantages to using <br />? Why wouldn't I want my HTML document to also be valid XML?Cecilla
@Aaron Franke: Valid XHTML is much more than just <br />. 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).Blue
"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 (╯°□°)╯︵ ┻━┻Libenson
K
441

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

Kroll answered 21/10, 2011 at 20:36 Comment(4)
IE10's Developer Tools is giving me "HTML1500: Tag cannot be self-closing. Use an explicit closing tag." on the line <meta charset="UTF-8" /> Any idea why that would be?Rube
Ok, I found out that self closing tags should not have the slash (and removing it fixes my error). Cite: tiffanybbrown.com/2011/03/23/…Rube
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.Rhombus
Regarding @SherylHohman's comment, I don't believe the spec has changed (or if it has, it has changed back). See w3.org/TR/html5/syntax.html#start-tags (8.1.2.1.6) - void (or foreign) elements may still include the slash.Slover
C
65

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

Communism answered 18/2, 2011 at 22:11 Comment(1)
"In practice, using self-closing tags in HTML should work just like you'd expect": <a name="foo" /> is a good example of where it does not. Instead of an anchor, you'll get the following text turned into a link. For <A> tag it is really important NOT to use self-closing syntaxSplendent
S
20

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.

Sanmicheli answered 24/8, 2010 at 15:28 Comment(0)
Y
6

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

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

Yarbrough answered 24/8, 2010 at 16:16 Comment(4)
According to HTML5 spec, self-closing syntax (/>) can't be used on a non-void HTML element.Update
The question was about self-closing tags on non-void elements, like <p/> or <div/>.Sanmicheli
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.Yarbrough
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.Sanmicheli
C
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

Courbevoie answered 24/8, 2010 at 15:28 Comment(1)
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.Zimmermann
V
1

Are (non-void) self-closing tags valid in HTML5?

Of course, they are valid but with little modification.

Take an example a self-closing tag <br>.

Even if you write <br/> or <br /> they will eventually be converted to <br> in the browser.

In self-closing tags ending with /> or />, / (slash) and white space will simply be ignored.

Take an example and let's see how it looks in the browser.

<p>This is paragraph with &lt;br&gt;<br> and &lt;br/&gt;<br/> and then &lt;br /&gt;<br />.</p>

The above code will look like the following image in the browser.

enter image description here

You can see all converted to <br>. So it's your choice to close the self-closing tag or not but they are completely valid.

Vasty answered 24/8, 2010 at 15:28 Comment(0)
S
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"/>
Sturrock answered 24/8, 2010 at 15:28 Comment(1)
That's because svg is written in xml, not html. It uses different parsing rulesPeele

© 2022 - 2024 — McMap. All rights reserved.