Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

html - Why do browsers think this <div/> tag isn't immediately ended?

Given the following HTML:

<div style="background-color:green"/>
<div>text</div>

Most browsers display the text in green which indicates that the <div/> shorthand is not recognized as 'ended' and it spans to wrap the 2nd <div>.

Or is this what the standard says?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strictly speaking, the <div> element is a non-void/non-empty element in HTML, i.e. it is not meant to self-close. Although <div /> is valid XHTML — due to /> being indicative of a self-closing (or empty) XML element — it's interpreted by common HTML parsers and some validators as an unclosed opening tag, and is therefore invalid HTML 4.01 and HTML5.1

In fact, running your given HTML fragment through the W3C validator (as HTML5) results in this error message:

Self-closing syntax (/>) used on a non-void HTML element. Ignoring the slash and treating as a start tag.

Hence what you see.


From the HTML5 spec (in the first link):

A non-void element must have an end tag, unless the subsection for that element in the HTML elements section of this reference indicates that its end tag can be omitted.

Following that, the subsection for the <div> element states:

A div element must have both a start tag and an end tag.

This makes <div> unlike <p> or <li> which are known to not always require an end tag.

If you place a <p> immediately after an unclosed <p>, it implicitly closes that previous <p>. Likewise goes for <li>. This is because you can't directly nest multiple paragraphs or list items together. However, <div> is nestable to any depth. Thus, an opening <div> tag does not close a previously-unopened <div> tag.

And that's why you're seeing what you're seeing.


1 In true XHTML pages (serialized as XML by serving as application/xhtml+xml), the first <div /> element will not expand to wrap the second <div>text</div> element. Instead, as XHTML it will follow XML rules and contain itself as an empty element, rather than follow HTML tag soup rules and be interpreted as an opening tag by itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...