问题
Possible Duplicate:
Using the XHTML closing slash (/) on normal tags?
Are self-closing tags valid in HTML5?
I'm reviewing a lot of HTML code and also JavaScript that synthesizes HTML and I noted that if there's some tag without content inside the tag then there're two way to specify it. Either like this:
<div id="container"></div>
or like this:
<div id="container" />
Is there any difference between the two?
回答1:
Browsers normalize invalid markup into the valid form:
<div />
is technically invalid markup (HTML 5), as div
is not a self-closing tag.
A browser will normalize it to <div>
.
Note that this is different from how XML will handle a self-closing tag compared to a closed tag.
A self-closing tag has no children and no value for inner text (null):
<foo />
A closed tag has no children and no inner text (empty string):
<foo></foo>
回答2:
<div id="container"/>
is the proper XHTML way of writing tags that contain no content. Typically these are <img/>
, <br/>
, and the like. <div>
is intended to have content inside it so saying <div id="container"/>
, while acceptable, seems less readable.
回答3:
The first example is strict HTML while the second is strict xHTML.
Pre HTML5, when you had to specify if you were using HTML or xHTML, using the wrong syntax would cause validation errors and sometimes rendering problems. Using the HTML5 doctype makes the difference moot.
Secondly, the second example is one of a self-closing tag, in this case an empty div
, but many tags in the xHTML spec support that, including img
, link
, meta
, and any other tag that would be otherwise empty.
来源:https://stackoverflow.com/questions/10726164/whats-the-difference-between-tag-tag-and-tag-in-html