Pseudorandom Knowledge

Semantic markup in HTML5

HTML5 introduces several new tags for semantic markup. The purpose is to replace the divs with home made classes and ids with something standardized. This will be helpful when the content is read by something other than a standard browser. The example below shows some of the main elements in the new system.

<body>
    <header>
      <h1>Site title</h1>
    </header>
    <nav>
        <a href="url">Link</a>
        <a href="url">Link</a>
    </nav>
    <section id="articles">
        <article>
            <h1>Heading</h1>
            <p>Paragraph text.</p>
            <h2>Sub heading</h2>
            <p>More text.</p>
            <section>
                <h1>Second sub heading</h1>
                <p>Even more text.</p>
            </section>
        </article>
        <aside>
            Advertisement
        </aside>
    </section>
    <footer>Copyright notice</footer>
</body>

The article tag is used for a self contained independent pieces, like a blog post or an article or anything that could be distributed on its own. A section is used to group related content together, for example a collection of articles or a set of paragraphs. There are also implicit sections. In the example above the article contains three sections of which only the last is explicit.

There is a lot more to say about sections in HTML5 and about all the other elements. Two things I will say though. Remember that header and headings are not the same. Secondly, you should still use divs in cases where new tags doesn’t make sense.

Browser compatibility

All modern browsers support the new elements. Most older browsers will handle the new tags the same way as spans. That means they are styled as inline by default. This can be fixed easily with a bit of CSS.

section, article, header, footer, hgroup, aside, nav {
  display: block;
}

However, this doesn’t work in Internet Explorer 8 and below which doesn’t allow you to style elements it doesn’t recognize. This can be fixed with the following workaround.

<!--[if lte IE 8]>
  <script>
    document.createElement("section");
    document.createElement("article");
    document.createElement("header");
    document.createElement("footer");
    document.createElement("hgroup");
    document.createElement("aside");
    document.createElement("nav");
  </script>
<![endif]-->

In reality there are more elements than these. You can either include them as you need or use a finished script that does this for you. Unfortunately this wont work if the user has disabled JavaScript. In that case the only thing you can do is inform them about it with a noscript tag and proceed without CSS for the new elements.