Tuesday, 4 December 2012

Determine a browser CSS3 capability and degrade gracefully using Modernizr

Support of HTML5 and CSS3 is improving all the time with the regular release of new browser versions. However this does make it difficult to keep up to date with what is supported by what.

The following two web sites provide similar functionality to help you determine what is fully or partially supported in what browser.

- http://html5please.com/
- http://caniuse.com/

Modernizr is described in wikipedia as

"Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation Web Technologies"

From the Modernizr download page you can now select only the tests you are interested in, reducing the footprint of the Modernizr file.

I chose just the CSS3 opacity test which generated a 14kb custom Modernizr file to download - "modernizr.custom.80211.js"

The following CSS3 sets rounded corners and opacity on all img tags.

img {
opacity: 0.5;
border-radius: 5px;

The following JavaScript will use Modernizr to determine if the browser supports the CSS3 opacity tag, if not it will download JQuery and use JQuery opacity function.

test: Modernizr.opacity,
nope: ['/Scripts/jquery-1.8.3.min.js'],
complete: function () {
if (!Modernizr.opacity) {
$("img").css("opacity", "0.3");

The following is a screenshot of the network tab in IE Developer tools using IE9 standards, we can see modernizr being downloaded and an image with rounded corners and opacity set.

The following is a screenshot of the network tab in IE Developer tools using IE8 standards, we can see JQuery being downloaded, the image still has opacity set but the corners are no longer round.