I am trying to understand why is there a difference in how a browser displays
verses ?Here is an example: The expected
Mainly because <div />
is not valid HTML.
If you have a look through the different doctypes you'll notice that div cannot be self closing.
According to the W3C:
A div element must have both a start tag and an end tag.
Source: http://www.w3.org/TR/html-markup/div.html
To include Chucks comment here also, a trailing slash in HTML does not a self closing tag make. Self closing tags using a trailing slash are a feature of XHTML, not HTML.
There are two questions here:
Why isn't this rendering correctly?
Is this valid HTML/XHTML/WhatNotML?
For question 1, the answer is simple: <div/>
isn't recognized tag soup, so if your browser is in tag soup mode, it won't handle it correctly. Serve your document as XML and you'll be fine, if you must use such constructions.
For question 2, the answer depends. In HTML 4.01 this is certainly not valid. For XHTML, new features were added to SGML to allow empty elements to use the "null end tag" (NET), but only when it follows the null-end-start-tag-closer immediately. The null-end start tag is <div/
, and the null end tag is >
, and letting the latter follow the former immediately yields <div/>
, which is fine. Any language using the XML SGML delcaration can express elements with no content as <foo/>
, whether or not foo
has declared content EMPTY or not.
A self closing div
tag is valid XML, but it's not valid XHTML.
The XHTML standard doesn't say anything specifically about whether the div
tag can be self closing or not, so it falls back on the HTML standard that the XHTML standard is based on. The HTML 4.01 standard says that the div
tag requires a closing tag.
As you have clarified that you're using HTML5... from the HTML5 spec:
Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single U+002F SOLIDUS character (/). This character has no effect on void elements, but on foreign elements it marks the start tag as self-closing.
The void elements are:
area, base, br, col, command, embed, hr, img, input, keygen, link, meta, param, source, track, wbr
The foreign elements are those from the MathML and SVG namespaces. As you can see, none of these elements are the div
element, and therefore your second example is invalid HTML5.
Its not rendered because it's an empty tag. "" != null.