How to Style HTML5 Elements with CSS
HTML5 introduces several new semantic elements, but you don't have to wait for browsers to support them before you can use them. That's because—believe it or not—most browsers allow you to style elements they don't yet support natively. Internet Explorer is the exception, but more on that (and a workaround) in a moment.
To clarify, CSS works as expected on previous HTML elements in an HTML5 page; it's just the elements unique to HTML5 that need a little help until browsers support them natively. Follow these three easy steps to start applying CSS to HTML5 elements in the meantime:
-
Add this to your site's main CSS file (the one all HTML5 pages use):
article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; }
Most modern browsers treat elements it doesn't recognize as inline elements. So, that bit of CSS above forces the new HTML5 block-level-like semantics to render as block-level in most modern non-IE browsers.
-
Internet Explorer (at least, versions 8 and older) ignores CSS on elements it doesn't natively support, unless you use JavaScript's
document.createElement("elementname")
to add each element to your page, a discovery credited to Sjoerd Visscher. For instance,document.createElement("aside")
tells IE to create theaside
element. Fortunately, there's a script available to take care of this for you, compliments of Remy Sharp.Add this to the head element (and only the head) of each of your HTML5 pages:
<!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->
You may also download
html5.js
and serve it yourself, though it is updated periodically, so it's not a bad idea to serve it from googlecode instead. (You can follow the script's progress at http://code.google.com/p/html5shiv/.)NOTE: Internet Explorer 9 is still under development, but it's expected to support many of HTML5's new elements. However, change
lt IE 9
tolte IE 9
in the conditional comment code in step 2 if it turns out IE9 doesn't allow styling them natively after all. -
Now, style away with CSS as you please.
You may run into the occasional glitch, but you'll be in good shape for the most part. Please note that your HTML5 documents still may not look as expected when printing from Internet Explorer.
BIG, BIG DISCLAIMER: Because styling HTML5 elements in IE requires JavaScript, users whose browsers don't support JavaScript or have it disabled will see un-styled, and undoubtedly messy, HTML5 elements! You might be OK with this risk if it's a personal site. However, if you're doing work for a client, I recommend getting their clearance before you use HTML5 elements. They may have user analytics concerning briwser usage to inform the decision, too.