Why do browsers think this <div/> tag isn't immediately ended?
Solution 1:
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.
1In 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.