Master responsive design with Modernizr

As you know, there is a lot more to building responsive websites than width. You need sensors that give you feedback to adjust sites based on other factors.

The best way to improve our feedback from your user’s sensor, or browser, is by using a JavaScript library called Modernizr. In this article I’ll explain why, when you go beyond width, Modernizr is such an invaluable tool.

In front-end development, developers used to adjust a site to fit the constraints of the layout engine used by a particular browser. In 2003, there were only three browsers: Netscape, Internet Explorer, and Opera. Firefox, Safari, and the first mobile browser, Opera Mini, were released by 2005. Chrome wasn’t released until 2008.

Currently there are five major browsers, each with its own mobile version. Across that array of browsers, there are also older versions that users haven’t upgraded. In the same way that creating multiple layouts for multiple screen sizes eventually becomes a zero sum game, so does building multiple front-ends for multiple browsers.

We’re using responsive web design to accommodate new, cutting edge mobile browsers. But, while accommodating new browsers, it’s important not to do so at the expense of older browsers.

Historically, optimization has come as a product of building a site for the most popular browsers and then tweaking to ensure the site looks the same on a set of popular browsers. Designs would have to accommodate the capabilities of all browsers.

Progressive enhancement is one strategy to cope with browsers’ failure to support modern features. There is a temptation to build for the most up-to-date features, but, in a responsive web, the design of a site is contextual to the frame that it’s being viewed through. Responsive web design has become popular because it resolves the most obvious changing context — the size of the frame — but the context of a browser runs much deeper than it’s viewport size.

SVG makes for a great solution for high-resolution displays, but what about its support in older browsers? It’s not supported in IE 8 or older, so you have to build in a fallback if you support that browser. You could identify the browser and serve alternative styles against that browser but then you would have to serve those same alternative styles for every browser that doesn’t support SVG.

Wouldn’t it be easier if you could just write a style that would be used against every browser that didn’t support SVG? That way, you wouldn’t have to keep up with bug reports from the users of older versions. You could just set the fallback once and forget it.

Traditionally, feature detection has been accomplished by detecting the browser’s user agent. This is done through JavaScript, using the navigator object. The navigator object dates back to the Netscape days and used to be a developer’s best tool in cross-browser compatibility.

If you have Chrome and have enabled DevTools, open your browser’s web inspector by right-clicking on a page and selecting Inspect Element. Then, click on Console and, after the caret, type “navigator.userAgent” and hit Enter. This will return your current browser’s user-agent, which is a string of text used to identify the browser in use. Chrome returns the following:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.35 (KHTML, like Gecko) Chrome/27.0.1443.2 Safari/537.35

In a lot of ways, the navigator object is the one of the best sensors we have available to us to inform our system about what our user is capable of; however, it’s not very future friendly. It bases your site’s actuators on a lot of assumptions about what the browser does and does not support. It also is unreliable because users can configure it to access sites that the browser might not be able to support.

What Modernizr does

Modernizr is a JavaScript library used to detect features in the browser. It’s loaded in the head of your page and runs during a page load. Adding it to your site is as simple as adding any other JavaScript library, such as jQuery, but, once added, Modernizer gives you an incredible amount of control in rendering your page and ensuring that every user is served a quality experience.

Having been loaded, Modernizr runs a series of checks against the user’s browser to determine what features the browser supports and creates a JavaScript object that you can use to test against. Modernizr doesn’t create support for these features; it simply gives you a way to provide fallback support for modern features. For example, in the case of SVG, Modernizr enables us to provide a fallback image for browsers that lack SVG support.

Modernizr also applies a set of classes to the HTML tag, giving you the ability to modify the page’s CSS using the corresponding CSS classes. These CSS classes allow you to use CSS systems to build actuators that will adjust your pages to allow the progressive enhancements available for a page.

As opposed to using the User Agent, Modernizr detects features directly by running a series of JavaScript tests that return boolean (true or false) values. This dictates the classes that are set to the html tag and gives you the ability to use JavaScript to detect whether a feature is available.

Installing Modernizr

Installing Modernizr is as simple as linking to the JavaScript library in the head of your page, but where the installation process gets complicated is creating the version that you need. Modernizr is available for download in two versions, the development version and the production version.

The development version is a full 42 KB, uncompressed file. This version is great if you’re well versed in JavaScript and want to make some tweaks to the tests it performs. Because it’s uncompressed, it’s easy to read and augment but it’s best left to developers with a firm understanding of JavaScript.

For those of you who might not be completely adept at JavaScript, or would like to quickly build a customized version of Modernizr, this is where the production version of the library comes into play. The production version building tool on the site gives you the ability to create a version with only the tests you require.

This comes in handy when you know you only need a certain set of tests. For instance, your site might not take advantage of CSS box-shadows, but it might need to support CSS gradients. Using the build tool, you can include the tests you need and exclude the ones you don’t need, keeping the source code trim and your user’s total load time down.

For our example, I’ll be working of the development version. I find that when I’m building a site, it’s best to work with the full version and then once you know what features you’ll be using in your site, trim the version down.

Using Modernizr for cross-browser CSS

Let’s do some simple feature detection with Modernizr. We’ll start with a raw sample site.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="js/modernizr.min.js"></script>
</head>
<body>
</body>
</html>

Let’s use this small test to detect whether or not our browser is capable of supporting SVG. For the sake of simplicity we’ll just add two span tags to the page to detect support.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="js/modernizr.min.js"></script>
<style type="text/css">
.yes{color:green;}
.no{color:red;}
span{display:none;}
.svg .yes{display:inline;}
.no-svg .no{display:inline;}
</style>
</head>
<body>
<div>
<span class='yes'>Huzzah! You have SVG support.</span>
<span class='no'>BOO! You don't have SVG support.</span>
</div>
</body>
</html>

If you test this in a browser that supports SVG, you’ll see the message “Huzzah! You have SVG support.” whereas if you have a browser that fails to support SVG, you’ll find the “BOO! You don’t have SVG support.” message.

This example is pretty rudimentary, but it displays the core idea of using Modernizr to fix cross browser issues. If we were doing this same fix using the old user agent method, we would have to have a style sheet for each browser that doesn’t support SVG and change our CSS for each one. (For anyone interested, the only major browsers lacking SVG support are Internet Explorer 7 and under.)

By adding the svg/no-svg class to the html on the page, your CSS now has a selector that can be used to override existing CSS rules. Because it’s on the parent-most tag, it can used to override other classes on the page.

So, in this case, both span tags are given display:none;. If there is no SVG support, the display:inline declaration on the span tag with the .no class overrides the display:hidden thanks to the no-svg rule on the html tag.

Let’s try a more useful example of the same idea. We might want to have an SVG background image on the page, which falls back to a PNG if the browser doesn’t support SVG. By default we’ll use the PNG image. This way, the SVG isn’t served unless it’s needed and becomes a progressive enhancement.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="js/modernizr.min.js"></script>
<style type="text/css">
.skull{
width:300px;
height:300px;
background-image:url(images/skull.png);
background-size:100% auto;
background-repeat: no-repeat;
}
.svg .skull{background-image:url(images/skull.svg);}
</style>
</head>
<body>
<div class='skull'></div>
</body>
</html>

Now we have an awesome SVG skull that will look awesome and crisp for users with high-resolution displays, and still look good for users with older browsers.

Summary

There is a great wealth of information to be learned about Modernizr. We showed you how it does the work of cross-browser capability without having to remember or maintain a running list of which browsers support SVG.

It functions exceptionally as a system with which to serve your user actuators to create speedy and highly functional websites.

Do you use Modernizr in your projects? What other methods have you used for serving responsive content? Let us know in the comments.

Featured image/thumbnail, divergent lines image via Shutterstock.

WDD Staff

WDD Staff

WDD staff are proud to be able to bring you this daily blog about web design and development. If there's something you think we should be talking about let us know @DesignerDepot.

Join to our thriving community of like-minded creatives!