Home > Articles > Web Development > HTML/CSS

This chapter is from the book

The Modernizr Library

If you have used HTML5 at all, you have undoubtedly heard of the Modernizr JavaScript library (http://modernizr.com). The Modernizr library allows you to test, on a feature-by-feature basis, what is supported by a visitor’s browser. You can use the dynamically generated classes for styling hooks in CSS, you can query a global Modernizr object that it creates, or you can do both, and then you can customize your pages to fall back when certain features are not supported.

Modernizr also includes a key feature called html5shiv, which solves a problem that exists in Internet Explorer version 8 and earlier. In Internet Explorer 8 and earlier, if you try to style an element that Internet Explorer does not recognize—for example, some of the new HTML5 elements, such as section or article—the element will not be styled. This problem prevented many designers and developers from using the new HTML5 semantic elements. In response, the web development community quickly came up with a solution. In January 2009, Remy Sharp created the HTML5 enabling script, which uses a technique first discovered by Sjoerd Visscher to get around the problem with Internet Explorer by simply creating the unknown elements programmatically via JavaScript. Modernizr leverages this same technique in its html5shiv to ensure that older browsers that don’t recognize the new elements are still able to apply styles to them.

But the real power of Modernizr is its ability to check for the presence of specific features. When you download Modernizr, you must specify which features you want to check for, as you can see in Figure 1.3.

Figure 1-3

Figure 1.3. Customizing a Modernizr build

As you read this book, you need a copy of Modernizr that can check for the following features:

  • CSS animations (also known as keyframe animations)
  • CSS 2D transforms
  • CSS 3D transforms
  • CSS transitions
  • html5shiv

The sample code for this book includes a production copy of Modernizr that is configured to check for all of these features. Instead of using the copy of Modernizr that comes with this book, you could customize your own build of Modernizr, selecting the features you plan on using in your website. Or, you could download the development version of Modernizr, which includes checks for all features and also consists of non-minified JavaScript code, so you can learn from the library and how it works. But for live websites, you will always want to use a production version that only checks for the features you will be using.

Leveraging the Modernizr Library

When you use a customized build for Modernizr, you need to reference it from the head element of your HTML page because the html5shiv enables HTML5 elements in Internet Explorer and so must execute before the body. HTML5 documentation also suggests that the Modernizr script be placed after the style sheet references. In Listing 1.1, we include the link to Modernizr in the head section, as well as a link to the two stylesheets we’ll be using, base.css and error.css (which will be defined later, in Listing 1.3).

Listing 1.1. Preparing a Page for Modernizr to Run (warning.html)

<html class="no-js" lang="en">
  <head>
    <link rel="stylesheet" href="css/base.css">
     link rel="stylesheet" href="css/error.css">
    <script src="js/modernizr.custom.57498.js"></script>
  </head>

Modernizr is particularly useful because it gives you a choice of how to use it. You can use it by writing conditional CSS or by querying the global Modernizr object that the library creates. This chapter focuses on using Modernizr to create styling hooks via CSS.

CSS Fallbacks via Modernizr

The first thing that Modernizr does when it runs is loop through all the features you’ve asked it to check for and make note of which ones are supported and which ones are unsupported by adding entries to the class attribute of the opening html element.

But before Modernizr can do its job, you need to set up one last thing with your page. You need to add the class no-js to the html element:

<html class="no-js">

When Modernizr runs, if your browser has JavaScript enabled, it will replace that class with the class "js":

<html class="js">

This gives you a styling hook that reflects whether JavaScript is enabled. Modernizr then adds classes for every feature it detects, prefixing them with no- if the browser doesn’t support it. For the custom build of Modernizr you use in this book, the latest version of Chrome generates the following:

<html class="js cssanimations csstransforms csstransforms3d csstransitions" lang="en">

The Default Message for Unsupported Browsers

For each animation you create in this book, you will leverage Modernizr to perform a check to see if the browser supports the features you need to run the animation. In the browsers that don’t have the proper support, you could provide, if you like, a default message that informs the visitor of the problem and provide links to download one of the new browsers with the appropriate support.

This message will consist of a simple div element, some text and links, and the most basic of styling. By default, this div will be styled to display: none. But if any of the required features you rely on for your animations are not present, a selector will follow the default styling to update this div to display and to add additional styles to it.

Listing 1.2 outlines the code for this fallback message, which is contained in the file warning.html. In addition to the fallback message, which includes an unordered list with links to the modern browsers, the listing includes a small div called #dismiss that can be used to close this message. Toward the end of Listing 1.2 you can find the JavaScript that hooks the #dismiss element up to a click event and then applies the style hide to the #unsupportedBrowser element upon click. You can find the complete warning.html file in the ch1code/ folder of this book’s GitHub project, available at: https://github.com/alexisgo/LearningCSSAnimations.

Listing 1.2. HTML and JavaScript for a Warning Message (warning.html)

<body>
  <div id="unsupportedBrowser">
    <div id="dismiss">
      <span>x</span>
    </div>
    <div id="warningText">
      Oh no! Your browser doesn't support CSS3 animations! Please download one of
      the following modern browsers in order to see what you're missing!


      <ul>
        <li><a href="http://www.mozilla.org/en-US/firefox/new/">Firefox</a></li>
        <li><a href="http://www.google.com/chrome">Chrome</a></li>
        <li><a href="http://www.apple.com/safari/download/">Safari</a></li>
        <li><a href="http://www.opera.com/">Opera</a></li>
        <li><a href="http://ie.microsoft.com/testdrive/">IE 10</a></li>
      </ul>
    </div>
  </div>

  <h1>YOYOYOYOYOYO</h1>

  <script type="text/javascript">
  window.onload = setup;

  function setup() {
    var dismiss = document.getElementById("dismiss");
    dismiss.onclick = hide;
  }
  function hide() {
    document.getElementById("unsupportedBrowser").className = "hide";
  }
  </script>
</body>

Listing 1.3 first styles the #unsupportedBrowser div to not display by default. Next, the code applies some basic styles to the unordered list. The fun kicks in after that, when you leverage Modernizr’s additions to the opening html tag in order to define a grouped selector. This grouped selector will be applied if even one of the key features is missing.

The grouped selector used will vary slightly based on each specific example used in the book, as not all examples use all the features checked for in Listing 1.1. Typically, the examples reviewed in subsequent chapters check for a subset of the list in Listing 1.3.

After the large grouped selector, let’s add some additional styles for the links, as well as the #dismiss div. Figure 1.4 shows what the warning looks like.

Figure 1-4

Figure 1.4. A default warning message that appears if the required properties for the CSS3 animation examples are not present.

Listing 1.3. Custom Style for an “Unsupported Browser” Message Added to H5BP Base CSS File (error.css)

#unsupportedBrowser, #unsupportedBrowser.hide { display:none; }

#unsupportedBrowser ul li {
  display: inline;
  list-style-type: none;
  padding: 0 10px;
}

#unsupportedBrowser ul  { margin:5px; }

.no-keyframes #unsupportedBrowser,
.no-cssanimations #unsupportedBrowser,
.no-csstransforms #unsupportedBrowser,
.no-csstransitions #unsupportedBrowser
{
  display: block;
  text-align: center;
  width: 100%;
  font-size: 0.8em;
  padding: 10px;
  background-color: rgb(15,70,131);
  color: white;

  -webkit-box-shadow: 0px 2px 2px rgba(0,0,0,0.2);
     -moz-box-shadow: 0px 2px 2px rgba(0,0,0,0.2);
          box-shadow: 0px 2px 2px rgba(0,0,0,0.2);
}

#unsupportedBrowser a { color:white; font-weight:bold; }

#unsupportedBrowser #dismiss {
  background-color: rgb(242,242,242);
  width: 25px;
  height: 25px;
  color: red;
  -webkit-border-radius: 13px;
  -moz-border-radius: 13px;
  border-radius: 13px;

  -webkit-box-shadow: 1px 1px 2px rgba(0,0,0,0.2);
     -moz-box-shadow: 1px 1px 2px rgba(0,0,0,0.2);
          box-shadow: 1px 1px 2px rgba(0,0,0,0.2);

  position:absolute;
  right: 3%;
  top: 2%;
  margin-left: 100px;
  font-size: 1.2em;
}

#warningText { margin:0 10%; }

While there are certainly more graceful and labor-intensive means to falling back when a visitor is using an older browser—namely, rewriting your animation with a library jQuery—the aim of this book is to focus on what you can do with the new technologies, not how to use old ones. Thus, rather than waste space reviewing old techniques, this book focuses on the new properties and how to use them most effectively.

One approach you might take when dealing with CSS3 animations is to fall back to a plain static object that doesn’t animate. That way, the animation is a bonus for modern browsers. In a real world project, it’s often best to allow the animation to degrade to a static object or group of objects.

Repeated CSS Property Definitions

There are times in this book when you will make use of another new CSS3 property, rgba, which allows you to add an alpha value to colors in order to make them semi-transparent. While Modernizr does support checking for this property, you can use a simple method to accommodate noncompliant browsers: Use repeated CSS property definitions.

Anytime you use the new rgba property, you preface that line with a simple background-color property. That way, if the browser does not support rgba, it simply ignores that line and applies the background-color property from the line before. For example, see the code in Listing 1.4.

Listing 1.4. Repeated CSS to Allow for Older Browsers

#someSelector {
  background-color: black;
  background-color: rgba(0,0,0,0.4);
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020