Front-end developer essentials – which DTD to use?

A DTD (document type definition) tells the browser what version of (X)HTML you are coding your web page in. Standards compliant pages must contain a DTD as the first item on the page otherwise it will not validate. Which one should you use?

An incomplete or no DTD may put your browser into quirks mode which means it will try to parse your code in a backwards compatible way and you might not get the results you were after. A list of the differences between quirks and standards mode is available on Wikipedia.

Current standards

Until earlier this year I would have suggested using the HTML4.01 strict doctype to enforce separation of content and presentation and excellent document structure.

<!DOCTYPE HTML PUBLIC
  "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">

With the development of HTML5 there is a new doctype that doesn’t have the URI to the document definition, because browsers didn’t follow it anyway. It has been retained to ensure all current browsers switch into standards mode. The HTML5 doctype is case-insensitive:

<!DOCTYPE html>

IE8 (and below) and Firefox 2 compatibility

IE doesn’t acknowledge that HTML5 elements exist. The content inside is rendered but the elements aren’t added to the DOM, so you won’t be able to style or reference them.

The simple fix for this is to add them by force using Javascript and Remy Sharp has created an HTML5 enabling script that you can hotlink from Google Code:

<!--[if IE]>
  <script src="http://html5shim.googlecode.com/svn/trunk/html5.js">
  </script>
<![endif]-->

A good explanation of how to add support for Firefox 2 is available at html5doctor.com.

Punkchip now brought to you in HTML5

This site now uses the HTML5 doctype, for two reasons. The first is that it is easy to remember off the top of your head and secondly, I have started to experiment with the new HTML5 elements such as header, article, section, nav and footer and I want my page to be validated as such.

Even if you aren’t going to start using the new elements or attributes you can still use the new doctype and get the benefits of standards-compliant browser rendering.

Further reading