Adobe
Products

Top destinations

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • SiteCatalyst
  • Students
  • Elements family

Adobe Creative Cloud

  • What is Adobe Creative Cloud?
  • Design
  • Web
  • Photography
  • Video
  • Students
  • Teams
  • Enterprise
  • Educational institutions

Design and photography

  • Photoshop
  • Illustrator
  • InDesign
  • Adobe Muse
  • Lightroom

Video

  • Adobe Premiere
  • After Effects

Web development and HTML5

  • Edge Tools & Services [opens in a new window]
  • Dreamweaver
  • Gaming [opens in a new window]

Adobe Marketing Cloud

  • What is Adobe Marketing Cloud?
  • Digital analytics
  • Social marketing
  • Web experience management
  • Testing and targeting
  • Media optimization

Analytics

  • SiteCatalyst
  • Adobe Discover
  • Insight

Social

  • Adobe Social

Experience Manager

  • CQ
  • Scene7

Target

  • Test&Target
  • Recommendations
  • Search&Promote

Media Optimizer

  • AdLens
  • AudienceManager
  • AudienceResearch

Document services

  • Acrobat
  • EchoSign [opens in a new window]
  • FormsCentral [opens in a new window]
  • SendNow [opens in a new window]
  • Acrobat.com [opens in a new window]

Publishing

  • Digital Publishing Suite

  • See all products
Business solutions

By business need

  • Digital analytics
  • Digital publishing
  • Document management
  • Media optimization
  • Social marketing
  • Testing and targeting
  • Video editing and serving
  • Web development [opens in a new window]
  • Web experience management
  • See all business needs

By industry

  • Broadcast
  • Education
  • Financial services
  • Government
  • Publishing
  • Retail
  • See all industries
Support & Learning

I need help

  • Products
  • Adobe Creative Cloud
  • Adobe Marketing Cloud
  • Forums [opens in a new window]

I want to learn

  • Training and tutorials
  • Certification [opens in a new window]
  • Adobe Developer Connection
  • Adobe Design Center
  • Adobe TV [opens in a new window]
  • Adobe Marketing Center
  • Adobe Labs [opens in a new window]
Download
  • Product trials
  • Adobe Flash Player
  • Adobe Reader
  • Adobe AIR
  • See all downloads
Company
  • Careers at Adobe
  • Investor Relations
  • Newsroom
  • Privacy
  • Corporate Social Responsibility
  • Customer Showcase
  • Contact us
  • More company info
Buy
  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers
  • Adobe Marketing Cloud sales [opens in a new window]
Search
 
Info Sign in
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Welcome,
My Adobe
My orders
My information
My preferences
My products and services
Sign out
My cart
Privacy My Adobe
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out Privacy My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Promotions
Estimated shipping
Tax
Calculated at checkout
Total
Review and Checkout
Adobe Developer Connection / HTML5, CSS3, and JavaScript /

Up and running with Modernizr

by Chris Griffith

Chris Griffith
  • chrisgriffith.wordpress.com
  • @chrisgriffith

Content

  • Getting started
  • CSS injected classes
  • JavaScript feature detection
  • The Modernizr loader
  • Using Shims and Polyfills
  • Dealing with Internet Explorer
  • Creating a production version
  • Where to go from here

Created

19 February 2013

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
CSS3HTML5JavaScriptmultiplatform
Was this helpful?
Yes   No

By clicking Submit, you accept the Adobe Terms of Use.

 
Thanks for your feedback.

Requirements

Prerequisite knowledge

  • Prior experience with JavaScript libraries will help you make the most of this article.

Additional required other products

  • Modernizr

 

User level

All

It is often said that the only constant in software development is change. In web development there is another constant: browser inconsistencies. One of the biggest challenges of developing on the web is that applications are viewed on a wide range of platforms, browsers, and devices.

How does a modern web designer or web developer know if a certain feature will be available on their target platforms?

One answer is Modernizr, a popular open-source feature-detection JavaScript library. Modernizr provides a wide range of solutions to help designers and developers take advantage of HTML5 and CSS3 despite uneven browser support.

Getting started

The first step, of course, is to download Modernizr. When you download Modernizr, you have the option to download either the full development version or create a custom version that only includes the features you intend to use. Since you have to load this script at the start of the page, you will want your version of the Modernizr library to be as lightweight as possible in your production environment. For now though, use the development version, which includes all of the supported features (see Figure 1).

Figure 1. Select the Development version to experiment with Modernizr.
Figure 1. Select the Development version to experiment with Modernizr.

To begin using Modernizr in your project you have to add the library to each page that will employ it. Here is a basic HTML5 document:

<!DOCTYPE html> <html class="no-js" lang="en"> <head> <meta charset="utf-8"> <title>Hello Modernizr</title> <script src="js/modernizr.js"></script> </head> <body> </body> </html>

The code above loads the modernizr.js file in the <head> element of the document rather than in the bottom of the page where scripts are usually placed for performance reasons. For all Modernizr features to work properly, this <script> tag must be included in the <head> section.

CSS injected classes

You will also notice that the <html> tag on the above page has a class of "no-js" attached to it. When Modernizr loads, it removes this class and replaces it with a "js" class. Then, along with the js class, the library will add classes for all the features that the browser supports and other classes for the features that the browser does not support.

For example, here is what the <html> tag looks like in a current version of Chrome:

<html class="js no-touch postmessage history multiplebgs boxshadow opacity cssanimations csscolumns cssgradients csstransforms csstransitions fontface localstorage sessionstorage svg inlinesvg blobbuilder blob bloburls download formdata">

Now compare that with that with the <html> tag in an older browser, Internet Explorer 7:

<html class="js no-touch postmessage no-history no-multiplebgs no-boxshadow no-opacity no-cssanimations no-csscolumns no-cssgradients no-csstransforms no-csstransitions fontface localstorage sessionstorage no-svg no-inlinesvg wf-loading no-blobbuilder no-blob no-bloburls no-download no-formdata">

You can use these injected classes in your CSS to style your content differently based on available support for particular features. For example, you might want to style your button elements to have a partially transparent background. The initial CSS might look like this:

.button { background: #000; opacity: 0.75; }

If the browser does not support CSS opacity, you’ll get a button with a black background instead of the grey semi-transparent button you want.

Using the ".no-opacity" class added by Modernizr, you can override the initial CSS with the following CSS to accommodate less capable browsers:

.no-opacity .button { background: #444; }

You can also approach this problem in the reverse manner, handling the base design and progressively enhancing it for more capable browsers; for example:

.button { background: #444; } .opacity .button { background: #000; opacity: 0.75; }

The method you use is entirely up to you and your design philosophy (enhancement vs. degradation). With each CSS rule targeting the support or non-support of a feature, your stylesheet may become quite complex. You also may need to consider how the page will appear if the Modernizr library is not loaded (for example, if JavaScript is disabled).

JavaScript feature detection

In addition to injecting CSS classes into your HTML, Modernizr also creates a JavaScript object within your document named Modernizr. This object enables you test each feature to see if it is supported by the browser. Here are a few simple examples:

Modernizr.cssgradients; //True in Chrome, False in IE7 Modernizr.fontface; //True in Chrome, True in IE7 Modernizr.geolocation; //True in Chrome, False in IE7 These tests can be used to create logic branches: if (Modernizr.canvas){ // Can use easeljs to draw! } else { // Provide some fallback } if (Modernizr.touch){ // Can’t use hover or rollover/rollouts events } else { // }

However, this approach can get quite messy as your code grows. A better approach is to conditionally load JavaScript resources based on the results of Modernizr tests.

The Modernizr loader

Bundled with the Modernizr library is an asynchronous conditional resource loader. Independently known as yepnope.js, this loader enables you to specify, based on the result of the given test, which JavaScript or CSS files to load. Here is an example:

Modernizr.load({ test : Modernizr.localstorage, yep : 'localStorage.js', nope : 'alt-storageSystem.js' Complete : function () { enableStorgeSaveUI();} });

In the above example, the loader tests to see if the browser supports localstorage. If it does, then it will asynchronously load the localStorage.js file. If the browser does not support localstorage functionality, then it will load the alt-storageSystem.js file instead.

You do not always need to fragment your code to support both the yep and nope cases. For example, you can use this mechanism to load only the needed JavaScript code and CSS for use on touch devices:

Modernizr.load({ test : Modernizr.touch, Yep : ['js/touch.js', 'css/touchStyles.css'] });

Using Shims and Polyfills

You can use Modernizr.load()to "patch" the browser with shims (bits of code that emulate missing browser functionality) and polyfills (a specific class of shims that aim to replicate missing functionality exactly). Thus, if a shim or polyfill for the feature is available, you can correct any missing features in a user’s browser when, for example, a client might require that the look or functionality match across all browsers.

A good example of this is the HTML5 input type for dates. On supported browsers we have access to robust datepicker

Figure 2. HTML5 Datepicker in Google Chrome
Figure 2. HTML5 Datepicker in Google Chrome

But this control is only supported in about half of the browsers. For about browser support of an HTML5 or CSS3 feature, I refer to http://caniuse.com/. But there is a nice fallback using jQuery UI to polyfill our page. By using Modernizr’s loading capabilities, we can load the four files needed to recreate a date picker for those browsers.

Modernizr.load({ test : Modernizr.inputtype && Modernizr.inputtypes.date, nope : [‘js/jquery.js’, ‘js/jquery-ui.js’, ‘css/jquery-ui.css’, ‘js/datepicker.js’] });

Two resources I use when I need a polyfill are HTML5Please and Webshims Lib. Both of these sites offer a great collection of solutions, but I recommend that you always research and understand a shim or polyfill before you use it so that you are aware of any potential issues that it might introduce.

Another bonus provided by Modernizr is that html5shiv is also included in the library. The html5shiv library enables older versions of Internet Explorer to correctly handle certain HTML5 sectioning tags (like <article> or <section>).

Dealing with Internet Explorer

Beyond the assistance of the html5shiv library in working with Internet Explorer, Modernizr also provides a set of CSS conditional classes. Modeled after HTML5 Boilerplate, these classes enable you to set CSS rules that target specific versions of Internet Explorer. By placing this HTML before your <html> element, these conditional will be triggered by Internet Explorer, along the proper CSS class associated with that version of Internet Explorer.

<!--[if lt IE 7]> <html class="no-js ie lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js ie lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js ie lt-ie9"> <![endif]--> <!--[if IE 9]> <html class="no-js ie lt-ie10"> <![endif]--> <html class="no-js">

For example, if your design relies using the box-shadow property, which is not supported in Internet Explorer 6 through Internet Explorer 8, you target those browsers with this custom CSS:

/* IE6-8 Specific Code */ body.lt-ie7 #box, body.lt-ie8 #box, body.lt-ie9 #box { zoom: 1; filter: progid:DXImageTransform.Microsoft.DropShadow(OffX=5, OffY=5, Color=#ff0000); }

Creating a production version

When you're ready to deploy your site, it's recommended to create a customized production version of Modernizr that contains only those elements that you actually need. This can reduce the size of the Modernizr library from 42 KB (uncompressed) to as little as 2 KB, depending on which features you choose. You can use the Modernizr download page to select the options you need (see Figure 2).

Figure 3. The Modernizr download page lets you choose only those features you need.
Figure 3. The Modernizr download page lets you choose only those features you need.

The options are conveniently grouped in categories: CSS3, HTML5, Miscellaneous, and Extra. There are some additional options for extensibility and non-core detection.

Where to go from here

There are many more ways you can use Modernizr in your next project. Take the time to read over the documentation for a complete overview of the library’s full capabilities. Also spend some time exploring HTML5Please and WebShims; they can be a great help in creating incredible experiences in almost any browser.

Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License+Adobe Commercial Rights

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

More Like This

  • Using CSS3 transitions: A comprehensive guide
  • The pursuit of simplicity
  • An Overview of Brackets' Code Architecture
  • Backbone.js Wine Cellar tutorial – Part 1: Getting started
  • JavaScript design patterns – Part 1: Singleton, composite, and façade
  • Getting started with PhoneGap in Eclipse for Android
  • Using the Geolocation API
  • Unit test JavaScript applications with Jasmine
  • Backbone.js Wine Cellar tutorial – Part 2: CRUD
  • Build a Hangman game with HTML5 Canvas, JavaScript, and CSS – Part 1: Creating the interface

Products

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • Digital Publishing Suite
  • Elements family
  • SiteCatalyst
  • For education

Download

  • Product trials
  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR

Support & Learning

  • Product help
  • Forums

Buy

  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2013 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy | Cookies

Ad Choices

Reviewed by TRUSTe: site privacy statement