Doctype
For my first post, I thought I would start off with the <!doctype>
tag, the first thing you write on any HTML document.
The <!doctype>
(Document Type Declaration) tag is what indicates to your browser and other HTML-parsing tools what version of HTML you are writing and therefore how to interpret it. Before HTML5, there were different co-existing versions of HTML you could use to markup your website. These versions all had slightly different ways of writing HTML, and accepted slightly different tags. So, you had to tell your browser which version of HTML you were writing, in order for your markup to be effective. For example, if you wanted to centre an element within your document, you could use a <center>
tag if you were writing HTML4.01 Transitional, but not if you were writing HTML4.01 Strict.
In my early days - i.e. when I used to just copy and paste code - I never considered what this tag really was and the effects it would have on what I wrote, and ran into a lot of problems with these cross-version differences.
W3Schools has an extensive list of the HTML elements and doctypes that support them if you are interested.
Why you still need to declare your doctype #
Because HTML5 is now the standard, if you skip on your doctype, most modern browsers will still be able to determine what you are writing. However, you should still declare your doctype for two main reasons.
Cross Browser Support (i.e., IE) #
Different browsers handle a missing or wrong doctype differently, and this can mess up the DOM. To test this out, I used the HTML5 <audio>
tag, but did not declare a doctype. In my css, I wrote a line targeting the <audio>
tag in addition to other styling.
audio { border: 10px solid red; }
These were the results across different browsers and versions.
Firefox 30 on Windows 8.1 - Works fine!
IE 9 on Windows 7 - The page was broken. None of my css rendered, including the css that wasn’t related to the <audio>
tag.
Opera 12.15, IE 6 on MacOSX - The entire page broke and nothing displayed at all.
Validation (aka, writing good code) #
As a developer, you want to write code that is as semantically valid as possible, and a doctype declaration is mandatory for your code to validate. There is a more extensive article by W3 on why you need to be writing valid code.
How to declare the doctype #
With HTML5 came the simplified document type declaration. Instead of declaring what specific iteration of HTML you want to follow, you only need to write:
<!doctype html>
This upholds your page to the standards of the latest version of HTML. You can find the methods to declare the other versions of HTML here if you are interested.
Please leave a comment below if you have any feedback, questions, or concerns.