Reputation: 21007
I always learned to close HTML tags like img
, meta
etc. like this:
<img src="..." />
<meta charset="..." />
<hr />
<br />
<input type="..." />
But I've seen numerous sites that don't put the />
at the end. They simply put >
at the end. Which results in:
<img src="...">
<meta charset="...">
<hr>
<br>
<input type="...">
But to me that doesn't seem right... How can a browser know if a tag still needs to be closed somewhere when you do it like that? That's also how I learned it years ago.
But even Twitter Bootstrap is closing input
tags without />
at the end.
Is this really valid HTML? And is it now a preferred way of doing it?
Upvotes: 1
Views: 219
Reputation: 943561
<foo />
is XML syntax. It is meaningful only in XML (including XHTML).
However, let us deal with HTML.
How can a browser know if a tag still needs to be closed somewhere when you do it like that?
Some elements have required end tags. These must have an explicit </foo>
Some elements cannot have any child nodes and must not have an explicit </foo>
. For example <img>
.
Some elements have optional end tags (such as <p>
). Browsers will close these elements when either they encounter an explicit end tag (</p>
) they they encounter the start tag for an element that is not allowed as a child node inside that element (such as a <div>
inside a <p>
or a <li>
inside another <li>
).
Browsers know which elements have required, optional or forbidden end tags because they are programmed to recognise HTML.
HTML 5 allows the />
syntax on elements either forbidden end tags, but that is just syntactic sugar for people addicted to XML.
Upvotes: 5
Reputation: 129
This is valid in HTML5, but not in XHTML. I personally prefer using this, just because is saves some bytes.
Upvotes: 0