结束 HTML 标签
什么时候适合使用结束标签,什么时候使用斜杠就足够了?
<div></div>
与
<div />
When is it appropriate to use a closing tag and when a slash is enough?
<div></div>
vs.
<div />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
(可以)包含某些内容的元素需要结束标记,例如
div
、a
和body
。对于仅由元素本身组成的元素,例如
img
、link
和br
,斜杠就足够了。Closing tag is needed for elements that (can) contain something, such as
div
,a
andbody
.Slash is enough for elements that consist only of the element itself, such as
img
,link
andbr
.如果您的 DOCTYPE 设置为 XHTML,则只能使用自结束标记
,因为这是从 XML 借用的,您可以在 XML 中使用自结束标记。如果您的 DOCTYPE 设置为 HTML 4.01 或 HTML 5,则无法拥有它。
http://www. w3.org/TR/xhtml1/
我不确定你想要这个的确切用例,但如果是为了清除浮动,你可以这样做,而不必担心兼容性问题,特别是对于 IE 如果它进入仿真模式。
You can only use a self closing tag
<div />
if your DOCTYPE is set to XHTML as this is borrowed from XML where you can have self closing tags. You can't have it if your DOCTYPE is set to HTML 4.01 or HTML 5.http://www.w3.org/TR/xhtml1/
I'm not sure your exact use case for wanting this, but if it's for clearing floats, you can do this instead and not have to worry about compatibility issues, especially with IE if it kicks into emulation mode.
不同之处在于,如果不使用结束标签,则只能设置标签的属性。
如果您需要在其中包含一些内容,则需要一个开始标签和一个结束标签,并将内容放在中间。
例如,如果您需要使用
跳过一行,从技术上讲,您也可以使用,但没有人以这种方式使用它,因为跳行之间永远不会有任何内容。
对于
,您可能会在其中包含很多内容,最后需要一个结束标记。
The difference is that if you don't use a closing tag, you will be able to set only the tag's attributes.
If you need some content inside it, you need both a opening and a closing tag, having the content in between.
For example, if you need to skip a line using
<br/>
, you could technically also use<br></br>
, but no one uses it that way, as a line skip will never have anything in between.In the case of a
<div>
, you will probably have a lot of content inside it, needing a closing tag in the end.如果您查看 HTML DTD(4.01 严格,作为5 dtd 仍在进行中,尚未发布),您将看到一些元素是用
EMPTY
定义的,这意味着这些可以是自关闭的。没有此定义的元素不能自关闭。例如,
br
元素:div
元素不是这样定义的,因此拥有自闭合永远是不对的div
。If you take a look at the HTML DTD (4.01 strict, as a 5 dtd is still in progress and has not been released yet), you will see that some elements are defined with an
EMPTY
, meaning these can be self closing. Elements that do not have this definition, cannot be self closing.For example, the
br
element:The
div
element is not defined this way, so it is never right to have a self closingdiv
.如果该元素是自包含的,并且具有在没有任何
innerHTML
的情况下呈现自身所需的一切,那么您可以使用简写
否则您应该使用If the element is self containing, and has everything that it needs to render itself without any
innerHTML
, than you can use the shorthand<hr />
otherwise you should use