modernizr: detect HTML5/CSS3 features not browsers, a simple quick start guide.

September 25th, 2012

In a recent project, I used the new css3 property for 3d transforms to scale down an iframe preview window for websites. In testing compatibility, I realized that IE doesn't yet fully support 3d transforms for css3 - go figure. As this was part of a progressive feature set anyways I decided I could live without it on IE browsers (who uses this anymore anyways? ... ok I'm just kidding). My immediate thoughts was to detect browser type and disable the preview feature for all IE browsers and boy did this bring on bad flashbacks of my IE6-IE7 design days or what.

I decided to look a bit harder for alternatives and that's when I find out there has been a huge push to move away from browser detection to feature detection (Jquery for example plans to depreciate it's $.browser method and promotes use of it's $.support method instead). The rational is simple, find out what a browser can do rather than judging a book by it's cover. 

This is where modernizr comes in, it's a simple quick javascript library that provides you a way to detect CSS3 / HTML5 feature capability on any browser. Here's how to use it:

  1. First configure your modernizr library to detect just the features you are looking for:
  2. Download the library and stick this in your <head></head>: <script src="/js/modernizr.custom.76025.js"></script>
  3. Now place class="no-js" in your html tag like this: <html class="no-js">
  4. Now simply use the modernizr object in your javascript to query for a specific feature, for example: if(modernizr.csstransforms3d) { ..... } and/or in your CSS: .csstransforms3d .content { ..... }

Conceptually how it works:

  1. Upon page load, modernizr runs quickly to detect feature capabilities of the browser.
  2. modernizr then replaces the "no-js" class (in your html tag) with a set of classes that correspond to the browser's capability. In this case, it replaces "no-js" with "js csstransforms csstransforms3d" so that your html tag will look like this: <html class=" js csstransforms csstransforms3d"> In explorer, the tag looks like this: <html class=" js csstransforms no-csstransforms3d"> (Why does it do this? So you can easily use css classes to transform your css-based design according to feature capability.)
  3. In Javascript, you can also programmatically use modernizr to detect features and enable certain features progressively. modernizr provides a modernizr object (called "modernizr"). To detect features, simply check the boolean property of that feature, in this example: <script type="text/javascript"> if (modernizr.csstransforms3d) { ... } </script> If transforms3d capability is present, it returns true, otherwise it returns false.

That's it. Hopefully this helps.