Html (非空)自闭合标签在 HTML5 中有效吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3558119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:15:09  来源:igfitidea点击:

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

htmlsyntaxw3c-validation

提问by cdeszaq

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

W3C验证不喜欢自闭合标签(那些一端与“/>上“)非空元素。(空元素是那些可能永远不包含任何内容的元素。)它们在 HTML5 中仍然有效吗?

Some examples of acceptedvoid elements:

可接受的void 元素的一些示例:

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

Some examples of rejectednon-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.

注意:W3C 验证器实际上接受 void 自闭合标签:作者最初因为一个简单的错字\>而不是/>)而遇到问题然而,一般来说,自闭合标签在 HTML5 中并不是 100% 有效,答案详细说明了各种 HTML 风格的自闭合标签问题。

回答by Quentin

  • 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>). This is an SGMLrule that browsers did a very poor job of supporting, and the spec advises authors to avoid the syntax.

  • In XHTML, <foo />means <foo></foo>. This is an XMLrule that applies to all XML documents. That said, XHTML is often served as text/htmlwhich (historically at least) gets processed by browsers using a different parser than documents served as application/xhtml+xml. The W3C provides compatibility guidelinesto 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.
  • HTML 4 中<foo /(是的,根本没有>)意味着<foo>(这会导致<br />含义<br>>(即<br>&gt;)和<title/hello/含义<title>hello</title>)。这是浏览器在支持方面做得很差的SGML规则,规范建议作者避免使用.

  • XHTML 中<foo />表示<foo></foo>. 这是适用于所有 XML 文档的XML规则。也就是说,XHT​​ML 通常用作text/html(至少在历史上)由浏览器使用与用作application/xhtml+xml. W3C的提供兼容性原则,要遵循XHTML的text/html。(本质上:仅当元素定义为 EMPTY 时才使用自闭合标签语法(并且 HTML 规范中禁止使用结束标签))。

  • HTML5 中, 的含义<foo />取决于元素的类型

    • 在被指定为无效元素的HTML 元素上(本质上是“在 HTML5 之前存在并且被禁止包含任何内容的元素”),结束标记被简单地禁止。开始标记末尾的斜线是允许的,但没有意义。对于沉迷于 XML 的人(和语法高亮者)来说,这只是语法糖。
    • 在其他 HTML 元素上,斜线是一个错误,但错误恢复会导致浏览器忽略它并将该标记视为常规开始标记。这通常会导致缺少结束标记,导致后续元素成为子元素而不是兄弟元素。
    • 外来元素(从 SVG 等 XML 应用程序导入)将其视为自闭合语法。

回答by Red Orca

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.

正如 Nikita Skvortsov 指出的那样,自动关闭的 div 不会验证。这是因为 div 是一个普通元素,而不是一个空元素

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

根据HTML5 规范,不能包含任何内容(称为void 元素)的标签可以自闭合*。这包括以下标签:

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.

然而,“/”在上述标签上是完全可选的,因此<img/>与 没有区别<img>,而是<img></img>无效的。

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

*注意:外来元素也可以自动关闭,但我认为这不在此答案的范围内。

回答by Michael Edenfield

In practice, using self-closing tags in HTML should work just like you'd expect. But if you are concerned about writing validHTML5, 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.

在实践中,在 HTML 中使用自关闭标签应该像您期望的那样工作。但是如果您关心编写有效的HTML5,您应该了解在您可以使用的两种不同的两种语法形式中如何使用此类标签。HTML5 定义了 HTML 语法和 XHTML 语法,它们相似但不完全相同。使用哪一种取决于 Web 服务器发送的媒体类型。

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.

很有可能,您的页面被用作text/html,它遵循更宽松的 HTML 语法。在这些情况下,HTML5 允许某些开始标签在终止 > 之前有一个可选的 /。在这些情况下, / 是可选的并且被忽略,因此<hr><hr />是相同的。HTML 规范称这些为“空元素”,并给出了有效元素的列表。严格来说,可选的 / 只在这些空元素的开始标签内有效;例如,<br />并且<hr />是有效的 HTML5,但<p />不是。

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

HTML5 规范明确区分了对 HTML 作者和 Web 浏览器开发人员正确的内容,第二组被要求接受各种无效的“遗留”语法。在这种情况下,这意味着符合 HTML5 的浏览器将接受非法的自闭合标签,例如<p />,并按照您可能期望的方式呈现它们。但对于作者而言,该页面将不是有效的 HTML5。(更重要的是,DOM树您使用这种非法语法的获得可以认真搞砸了;自我封闭的<span />标签,例如,倾向于把事情搞得一团糟了不少)。

(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 requiredfor those elements defined as such.)

(在您的服务器知道如何将 XHTML 文件作为 XML MIME 类型发送的特殊情况下,页面需要符合 XHTML DTD 和 XML 语法。这意味着那些定义为此类的元素需要自关闭标签。)

回答by thomasrutter

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

HTML5 基本上表现得好像尾部斜杠不存在一样。HTML5 语法中没有自关闭标签这样的东西。

  • Self-closing tags on non-voidelements 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 voidelements like <br/>or <img src="" alt=""/>willwork, but only because the trailing slash is ignored, and in this case that happens to result in the correct behaviour.

  • 诸如, 之类的非空元素上的自闭合标签根本不起作用。尾部斜杠将被忽略,这些将被视为开始标记。这很可能会导致嵌套问题。<p/><div/>

    无论斜杠前面是否有空格,这都是正确的:<p />并且<div />由于同样的原因也不会起作用。

  • void元素上的自闭合标签像<br/>or<img src="" alt=""/>起作用,但只是因为忽略了尾部斜杠,在这种情况下,这恰好导致了正确的行为。

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.

结果是,在旧的“XHTML 1.0 作为文本/html”中工作的任何内容都将继续像以前一样工作:那里也不接受非空标签上的尾部斜杠,而 void 元素上的尾部斜杠工作。

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.

还有一点要注意:可以将 HTML5 文档表示为 XML,这有时被称为“XHTML 5.0”。在这种情况下,将始终处理 XML 规则和自闭合标签。它总是需要与 XML MIME 类型一起提供。

回答by Andreas Herd

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

我的直觉会<span></span><span></span>改为

回答by Nick

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

自闭合标签在 HTML5 中有效,但不是必需的。

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

<br>并且<br />都很好。

回答by Leo

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"/>