Wednesday, November 7, 2012

Doctypes: What are they and why should you care?

Imagine walking into a room where everyone speaks english, but they all come from different countries, and different sections of each country.  It's all the same language, but the words they use can mean different things to each person.  For instance, somebody from England might ask you to "fetch a torch from the boot".  To an American, that wouldn't make much sense unless you knew to expect the British version of English.  Then you'd know that he was asking you to get a flashlight from the trunk of his car.

A doctype can be thought of as a definition of what variation of language your page is written in.  If you don't specify a doctype, each browser will try to interpret things their own way and the results can either be subtly different or completely off, so a doctype should be considered mandatory.  Unfortunately, they are very often forgotten about until after you've spent hours or even days trying to figure out why your page isn't working as it should.

The following list does not cover EVERY possible doctype, just the most common ones.  The doctype needs to be the first line in your code, even before the <html> tag itself.  Make sure to preserve the exact case of the lines listed below... it's better to copy and paste them rather than trying to retype them, since even a slight mistake can mean that your doctype is invalid and is essentially the same as not having one at all.

If you don't know which one you want, I suggest going with either HTML 4.01 Loose or HTML 4.01 Strict.  The Loose version gives a good amount of flexibility by allowing deprecated elements and attributes. The Strict version does not allow these deprecated elements, but does offer more power when it comes to making advanced javascript work.  Some javascript libraries or plugins will require Strict, which is usually explained in their documentation.

One example of a deprecated element is the <font> tag.  HTML 4.01 Loose will allow you to write <font color="#f00">Red text</font> The new technique for HTML4.01 Strict is <span style="color: #f00;">Red text</span> or some variation such as <span class="redColor">Red Text</span> (where redColor is defined in CSS elsewhere)

HTML 4.01 (w3 definition)
Strict<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "">
Transitional<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
Frameset<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "">

XHTML 1.0 (w3 definition)
Strict<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
Transitional<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
Frameset<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "">

NOT a standard yet
Browser support varies

Further Reading:

No comments:

Post a Comment