Optional Tags in HTML5

I’ve been learning a lot about HTML5 lately, and have found much of it to be pretty easy to adapt to. I found one bit of newly acquired HMTL5 knowledge blog-worthy: the fact that the <html>, <head> and <body> tags are optional!

After coding HTML since 1997, I’m pretty used to the standard elements for any new HTML or XHTML document (leaving out the good-practice bits for simplicity-sake).

[gist id="598365"]

These have become the staple of any Web developer. As you might imagine, the fact that the same document can be written as follows was quite a shock!

[gist id="598367"]

We’re free! We’re free!

Not quite, I’m afraid. As it turns out (I know this will be a shock to some of you), omitting these tags has a few undesirable side-effects that will leave some of your visitors dead in the water. The first of our offenders is the lack of a specified primary language for the document in the <html> tag. Excluding this will prevent screen readers from being able to determine the language of the page, preventing your site from being read consistently.

The next issue is derived in my favorite browser of all time – Internet Explorer (can you hear the sarcasm oozing forth?). Apparently, Microsoft deemed it necessary to prevent a page’s HTML5 elements from rendering correctly in the absence of a <body> tag, even with the hack of initializing the elements in Javascript, IE gets all pissy and still treats the elements as red-headed step children. Why? Yeah, we don’t know either.

Lastly, omitting these tags simply renders your code less readable. That one is simply something to consider. Those who know me well know that I’m a formatting nazi.

After all of this, the safest way to write our aforementioned code would be something like this:

[gist id="598376"]

So, what’s different about this compared to the old and busted version? For starters, we were able to shorten the doctype to simply “html”. In modern browsers, declaring a doctype is only used to trigger standards mode, but declaring something is necessary. Another difference is the missing quotes around en. Not a big deal, but it is certainly noteworthy that quotes are no longer required in order for the code to validate.

Leave a Reply