by

Modernizr

We don’t need this anymore

With Modernizr v2.7.0 we don’t need this work around anymore. Please update to this version if you use <main>.

tl;dr: You can add the new main-element to Modernizr 2.6.2 by using HTML5 Shiv’s window.html5 option to add your own elements to the shiv.


Since I use some bleeding edge stuff in HTML and CSS in actual projects for clients I ran into one particular issue a couple of times lately and I thought I share a little workaround with you.

Modernizr’s current state

Modernizr includes HTML5 Shiv to make HTML5 elements like header, figure and time known and styleable in old IE. Due to development for Modernizr version 3 the current version is Modernizr 2.6.2 which was published nearly a year ago (September 2012) when the main-element wasn’t around yet. Thus the version of HTML5 Shiv does not include a shiv for the main-element.

Today main is part of the HTML5 specification and is implemented in Chrome, Firefox and Safari Nightlies. You can read more about its value especially for semantics and accessibility on MDN and in a recent article at HTML5 Doctor.

The guys behind HTML5 Shiv included the main-element some time ago (you can learn more about the process of including some kind of default styling for the element in another HTML5 Shiv issue (thanks Mathias for the pointer)) and it is available in version 3.6.2. Sadly the latest stable version of Modernizr only includes version 3.6.1 of the shiv and there is no date set for a new release of Modernizr since everyone on the team tries to push version 3 to be out as soon as possible which will them include the new version of the shiv.

The Workaround

Until then we need to work around the missing shiv for the main-element (along with dialog and template).
Luckily it is possible to extend the list of elements HTML5 Shiv operates upon via its html5.elements option that we can use as needed.

First of all we need to create an object html5 on the window object and then add all elements that we want to be shiv’d.

window.html5 = {
  elements: 'abbr article aside audio bdi canvas data datalist details dialog ' +
      'figcaption figure footer header hgroup main mark meter nav output progress ' +
      'section summary template time video'
};

It is useful to take the list from the current version of the shiv to include all elements that need the shiv.

This code needs to be included before Modernizr is actually invoked so it might be useful to place it inline right before you insert Modernizr itself.

There is another way to include only specific elements like for example the main-element after Modernizr is already included:

window.html5.elements = 'main';
window.html5.shivDocument(document); // re-invoke the `shivDocument` method

Conclusion

This method is pretty straightforward and saves you a lot of time debugging or working around the inclusion of the main-element if you use Modernizr anyway.