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类型提供服务。
(Theoretically) in HTML 4, <foo / (yes, with no > at all) means <foo> (which leads to <br /> meaning <br>> (i.e. <br>>) 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.