My SGML is rusty, so I'm going to hope someone comes along to correct some of this but...
This line is SGML which is a super set of HTML and XML.
<!doctype html>
The <!
indicates that the document should drop back to follow SGML directives, not the parent document. This is the same reason that <!--
is the way to start a comment in XML and HTML. <!
drops to SGML, and --
is the usual delimiter for comments in SGML. In the above line of code, <! doctype html>
is valid SGML for declaring the doctype.
Whereas this line is a part of the standard document and needs to follow the documents rules (which are declared by the doctype, or schema dependent on the document):
<meta charset="utf-8">
In this the SGML rules no longer apply as we are looking at something that needs to conform to HTML. Now, depending on if it is HTML4, HTML5 or XHTML how the tag is closed changes.
In HTML4 many tags didn't need to be closed, and in fact in some cases were forbidden from being closed. This includes <meta>
, <img>
and <p>
tags, where only the latter was allowed to be closed (like </p>
) the other 2 should be left as is with attributes and no closing tags - because in their declaration they needed no closing tag.
However, in XHTML attempts were made to make HTML conformant to XML. A noble goal, however this meant that standalone tags line <meta>
or <img>
needed to be self-closing as they had no content and became <meta />
and <img />
in XHTML. However, people being overzealous started to do this in HTML4 documents as well. Technically invlaid, but most HTML parsers are very kind and eat much worse HTML, so they never really paid attention.
When HTML5 came along, everyone recognised that people were writing self-closing tags in HTML and the W3C said, "hey you know what, if everyone is doing it, let them do it legally". So, now in HTML5 you can have either <meta>
or <meta />
.
As for which type you should choose when writing your code. If you are outputting XHTML, you need to self-close the tag, no questions asked. Otherwise, you have options:
Arguments against self-closing:
- Over thousands of page views the additional space and slash add up. Google does some heinous things to make readable HTML that saves bytes - for a while they omitted
</body>
and </head>
closing tags.
Arguments for self-closing:
- Closing tags and making your HTML close to XML, makes it easier for XML based parsers to read your content, which may make searching or scraping content easier if you are using XML based technologies like XPath.
The choice is really up to you, but regardless of which approach you take, consistency is the key.