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?
The div tag is known as Division tag. The div tag is used in HTML to make divisions of content in the web page like (text, images, header, footer, navigation bar, etc). Div tag has both open(<div>) and closing (</div>) tag and it is mandatory to close the tag.
<div>: The Content Division element. The <div> HTML element is the generic container for flow content. It has no effect on the content or layout until styled in some way using CSS (e.g. styling is directly applied to it, or some kind of layout model like Flexbox is applied to its parent element).
What Is a Void Element? The void elements or singleton tags in HTML don't require a closing tag to be valid.
If you don't add a closing tag the browser won't know where it ends. It will take the next tag and think it belongs to the previous tag without the closing tag.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With