Specifying the correct doctype of your web page is very important. Without it, the client (the web browser, iPhone, etc) will have no idea which version of HTML you are using to write the document, and will default to guessing how the HTML should be rendered. In many browsers, this is known as “Quirks” mode, and can result in pages displaying oddly. By specifying the doctype, we tell the client “try to render this document according to the standards of this specification”. That information is added at the very start of the page, as follows:
<?xml version=“1.0” encoding=“utf-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
For HTML 5
The first part of the specification for XHTML – the xml prolog – shows the close relationship between XHTML and XML. A strictly coded XHTML document can be parsed as XML, if we ever wanted to do so. That first line tells the browser what version of XML the XHTML can be translated to (
1.0) and the character set used on the page (
utf-8, a version of Unicode). This line acts to “future proof” our work, and means that it will be readable for many, many years to come. That being said, the xml prolog is optional: you can drop it if you wish to).
The next line for XHTML, and the only line for HTML5 – the
doctype – tells the browser which version of HTML we are using (XHTML 1.0 Strict and HTML5), what language it is written in (English), and where to find the defining document for the specification.
Note that neither the doctype nor the XML prolog are, strictly speaking, part of HTML, and they largely ignore the rules that I lay out so carefully in subsequent articles. You may wish to think of the doctype and xml prolog as a negotiation or an exchange of information between the web page and the browser, much as you might, upon meeting a stranger in Switzerland, attempt words in several different languages before both parties settle on speaking English. In our case, our web page is saying “Hi. I can give you the information that follows as XML or XHTML, whichever you prefer. Oh, and I'm going to speak in English, formating my characters this way (UTF-8), just so you know.”
doctype is also required to validate our code, to check that we have written our web page in the right way. Without a doctype, the validator has no idea what version of HTML you are using, or what rules to check your code against.