Search code examples
htmldoctypehtml4

Do HTML5 elements "work" in non-HTML5 doctypes?


I did some internship at a company for re-newing their website. The "problem" was that they are still using a 4.01 doc type, so I hadn't had the chance to get some nice HTML5 going, I thought. But then I saw that some one else implemented a responsive menu with the <nav> tag and it worked. I am confused:

  • What exactly does the (HTML5) doctype do?
  • If HTML5 elements are displayed correctly in HTML4, what is the difference between the two then?

Solution

  • The HTML5 doctype serves exactly one purpose: to trigger standards mode. That's it. The HTML5 spec actually states this outright:

    Note: DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications.

    This specific construction of the doctype is the minimum necessary to trigger standards mode in all major browsers while preventing the document from being mistaken for some other document type. In SGML, this "HTML5 doctype" is essentially meaningless because it has neither a system identifier nor a public identifier. But no one has ever implemented SGML anyway (not even HTML in any of its SGML-based variants), which means browsers will ignore that fact and happily render markup in standards mode.

    Whichever doctype you use does not affect how a browser renders the markup or implements the relevant APIs, as long as you have one. That is to say, the "standards mode" used by browsers is the same whichever doctype you use. Validators do use the system or public identifiers in a doctype declaration to decide which standard to validate the markup against, but browsers never use this information to decide whether or not to support a feature.

    Of course, it should go without saying that if you have access to the HTML source, you should switch to the HTML5 doctype if you're using HTML5 features. There really isn't any reason not to.