W3C验证器(Wikipedia)不喜欢非void元素上的自关闭标记(以“/>”结尾的标签)。(空元素是那些可能永远不包含任何内容的元素。)它们在HTML5中仍然有效吗?
一些公认的void元素的例子:
<br />
<img src="" />
<input type="text" name="username" />
一些被拒绝的非空元素的例子:
<div id="myDiv" />
<span id="mySpan" />
<textarea id="someTextMessage" />
注意:
W3C验证器实际上接受无效自关闭标记:作者最初有一个问题,因为一个简单的拼写错误(\>而不是/>);然而,一般来说,自关闭标签在HTML5中并不是100%有效的,并且答案详细阐述了各种HTML风格的自关闭标签的问题。
HTML5的基本行为就好像末尾的斜杠不存在一样。在HTML5语法中不存在自关闭标记。
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.
结果是,任何在旧的“XHTML 1.0充当文本/html”中工作的东西都将继续像以前那样工作:在非void标记上的尾斜杠也不被接受,而在void元素上的尾斜杠则可以。
另外需要注意的是:可以将HTML5文档表示为XML,这有时被称为“XHTML 5.0”。在这种情况下,应用XML规则并始终处理自关闭标记。它总是需要使用XML mime类型提供服务。
自关闭的div将不生效。这是因为div是一个普通元素,而不是一个void元素。
根据HTML5规范,不能有任何内容的标签(称为void元素)可以自关闭*。这包括以下标签:
area, base, br, col, embed, hr, img, input,
link, meta, param, source, track, wbr
然而,上述标签上的“/”是完全可选的,因此<img/>与<img>没有区别,但<img></img>是无效的。
*注意:外部元素也可以自关闭,但我不认为这在这个答案的范围内。