Using HTML5 Today part 2–Fixing Semantic tags with a Shiv

Posted by Steve Albers on Geeks with Blogs See other posts from Geeks with Blogs or by Steve Albers
Published on Thu, 15 Mar 2012 23:26:12 GMT Indexed on 2012/03/18 17:59 UTC
Read the original article Hit count: 380

Filed under:

Semantic elements and the Shiv!

This is the second entry in the series of demos from the “Using HTML5 Today” talk.


For the definitive discussion on unknown elements and the HTML5 Shiv check out Mark Pilgrim’s Dive Into HTML5 online book at http://diveintohtml5.info/semantics.html#unknown-elements


Semantic tags increase the meaning and maintainability of your markup, help make your page more computer-readable, and can even provide opportunities for libraries that are written to automagically enhance content using standard tags like <nav>, <header>,  or <footer>.

Legacy IE issues

However, new HTML5 tags get mangled in IE browsers prior to version 9.  To see this in action, consider this bit of HTML code which includes the new <article> and <header> elements:

article

Viewing this page using the IE9 developer tools (F12) we see that the browser correctly models the hierarchy of tags listed above:

ArticleIE9

But if we switch to IE8 Browser Mode in developer tools things go bad:

ArticleIE8

Did you know that a closing tag could close itself?? The browser loses the hierarchy & closes all of the new tags.  The new tags become unusable and the page structure falls apart.

Additionally block-level elements lose their block status, appearing as inline. 

 

The Fix (good)

The block-level issue can be resolved by using CSS styling.  Below we set the article, header, and footer tags as block tags.

article, header, footer {display:block;}

You can avoid the unknown element issue by creating a version of the element in JavaScript before the actual HTML5 tag appears on the page:

   <script>
        document.createElement("article");
        document.createElement("header");
        document.createElement("footer");
    </script>

The Fix (better)

Rather than adding your own JS you can take advantage of a standard JS library such as Remy Sharp’s HTML5 Shiv at http://code.google.com/p/html5shiv/

By default the Modernizr library includes HTML5 Shiv, so you don’t need to include the shiv code separately if you are using Modernizr.

© Geeks with Blogs or respective owner