HTML5 and CSS3... Now!

Page 1

HTML5 and CSS3... Now! Written by Sandro Alberti; sandro@fen-om.com Sandro is a Web designer/developer who enjoys educating others about design, both in theory and practice.

INTRODUCTION

This is a review of 4 popular code methods that you can use, that allow you to detect exactly what level of HTML5/CSS3 your visitors are able to experience, and implement a custom experience for a wide range of visitors. I will also look at Compass, a CSS framework that allows you to produce proper CSS3.

CSS3 (AND HTML) DETECTION

The first method I'll review is Modernizr, a small JavaScript library that detects the presence of HTML5 and CSS3 features in the browser. It allows you to know when you can rely on browser functionality in order to implement your design. If you need to fall back on JavaScript for alternate styling, Modernizr can be used together with a script library called yepnope, which allows for the most efficient loading of helper JavaScript. Modernizr and yepnope can be downloaded here:

www.modernizr.com http://yepnopejs.com

Also by the people who make Modernizer, there is: Selectivizr, a JavaScript utility that emulates CSS3 pseudo-classes and attribute selectors in Internet Explorer 6-8. http://selectivizr.com

A third method is Google Chrome Frame. It also allows you to start using open web technologies - like the HTML5 canvas tag - right away, even technologies that aren't yet supported in explorers like Internet Explorer 6, 7, or 8. This is done through a plug-in that makes your Web site appear to be running in Google Chrome (and thus be able to experience HTML5). You can get it here: http://code.google.com/chrome/chromeframe/

Finally, we'll review CSS3 PIE ('Progressive Internet Explorer'). Like Selectivizr and Chrome Google Frame, this is a tool that allows particular effects, in browsers that can't normally display them; specifically: IE 68 can be made to display CSS3 effects such as border-radius, border-image, box-shadow, css3 backgrounds, gradients, png transparency, and rgba color values. http://css3pie.com

Modernizr (with yepnope) The main download of Modernizr is a single JavaScript file that you point to from your Web pages (modernizr.js). You also should add the following to the head of your Web pages: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" class="nojs">

This is the default setting in case Javascript is turned off or unavailable. The most common way of using Modernizr is to rely on the HTML classes that it automatically adds to your html tag. Looks something like this, as seen in my local browser: (but you can't see it in normal page source; you have to view 'generated source' since this is created via JavaScript)

Page 1


<html class="js canvas no-touch geolocation no-websqldatabase indexeddb hashchange history draganddrop no-websockets rgba hsla boxshadow textshadow opacity no-cssanimations csscolumns cssgradients no-cssreflections no-csstransforms3d csstransitions fontface video audio localstorage no-sessionstorage borderradius borderimage" lang="en">

All those classes tell you which features are available for you to play with, in that particular browser. For example, above, there is @font-face, and CSS3 box-shadow and text-shadow, but we don’t have websockets or 3D CSS transforms (these are prefixed with 'no-'). This means they will not be available. These become both classes at the html level, and testing mechanisms for the features themselves. For example, to test for border-radius (rounded corners), you style the element in a cascading path down from the html parent (which has a class of 'borderradius'). So, if you have an element of class 'box' in your page, you can add (and test for) border-radius like this: .borderradius .box { -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; } .no-borderradius .box { // fallback code providing an alternate styling to older browsers }

If Modernizr created a class of 'borderradius' in the html tag, then, logically, .borderradius .box will be implemented. On the other hand, if the html tag has been given a class of 'no-borderradius', then .borderradius .box can't be implemented. Note: .no-borderradius (or any Modernizr 'no-' class) is an extra feature for the older-browser fallback, useful if you happen to have older styles that could reproduce what is missing (for example, in the case of box-shadow, a shadow can be faked, old-school, with 2 border strokes). Some other css, such as font-face, might be more involved (apart from the basic Modernizr test, you first also have to declare/define the font-face itself; even if it's not used, it has to be declared first). Something like: @font-face { font-family: NAME_OF_FAMILY; src: local('NAME_OF_FONT'), url(NAME_OF_FONT_FILE.TTF) format('truetype'); }

Modernizr tests for CSS, HTML, and 'miscellaneous', including: • CSS: font-face, borders, shadows, CSS animations, reflections, columns, etc. • HTML: canvas, drag-and-drop, html5 audio, input attributes and types, localstorage, etc. • Miscellaneous: SVG, touch support, WebGL, etc. See a full list of supported features on the Modernizr site

Even more features can be detected with other JavaScript files on github: Additional feature-detects

The Problem: Sometimes, apart from Modernizr, you might have other scripts that implement lost functionality in older browsers (for example: if the browser can't show css3 shadows, you might have

Page 2


another script that fakes shadows in older browsers). In those cases, you are required to download the scripts even if a browser does support the HTML5/ CSS3. Enter yepnope.js. Yepnope loads scripts only if certain conditions are met. The best part is that it integrates beautifully with Modernizr, so everything just snaps into place. Yepnope is actually being included in special builds of Modernizr, because it's such a good companion (known as Modernizr.load). You could use yepnope to load additional scripts that will help provide support, if it doesn't exist already. In this example, we test for the email input type with Modernizr. If it is not supported, we load the h5f script, which emulates input types, and (with a callback) we run the h5f script: yepnope({ test: Modernizr.inputtypes.email, nope: 'h5f.min.js', callback: function(url, result, key) { H5F.setup(document.getElementById("signup")); } });

Selectivizr Since we are starting to touch on the topic of scripts that reproduce or emulate lost behavior in old browsers), the same people who make Modernizr, also make: Selectivizr. According to their literature, Selectivizr adds support for 19 CSS3 pseudo-classes, 2 pseudo-elements and every attribute selector to older versions of IE (IE 6 through 8). This is not for visual effects, but for selectors such as :first-child, :hove, :focus, etc. Basically, it runs if it detects IE6 through 8: <script type="text/javascript" src="[JS library]"></script> <!--[if (gte IE 6)&(lte IE 8)]> <script type="text/javascript" src="selectivizr.js"></script> <noscript> <link rel="stylesheet" href="[fallback css]" /> </noscript> <![endif]-->

It has to run in conjunction with a JavaScript library like JQuery, although, note: JQuery will not reproduce all of the behavior (it will not support :nth-last-child, :nth-of-type, :nth-last-of-type, :first-oftype, :last-of-type, or :only-of-type). Full support of Selectivizr is only offered by the NWMatcher JavaScript library. Note: Since Selectivizr only focuses on selectors, you can combine it with something like PIE (below) to take care of other aspects of CSS3. Google Chrome Frame This online technology "brings Google Chrome's open web technologies and speedy JavaScript engine to Internet Explorer". Many major websites such as yahoo.com, wordpress.com and several Google properties have adopted Google Chrome Frame. Besides giving their users access to a more modern web experience for many sites, Chrome Frame also presents a significant improvement in initial load time.

Page 3


Basically, it emulates Chrome in IE, although it doesn't reproduce the Chrome browser completely. Minor differences include: AppCache: Chrome Frame uses Internet Explorer’s network stack. Pop-up windows (window.open): Can be scripted by the calling page only if the popup window URL is in the same origin as the calling page. Context Menu: Chrome Frame pages display Chrome’s context menu. Page Information: The Page properties menu option in Internet Explorer will not display reliable page information. IE Encoding Menu Option: Will not work. IE Color Settings/ Fonts: Will not be honored. IE Extensions/ Add-Ons (Google Toolbar, etc): Will not work. A single line of code detects if a page visitor has Google Frame installed: <meta http-equiv="X-UA-Compatible" content="chrome=1">

If not installed, it can direct them to an installation page (yes, the plug-in has to be installed on the user end; it then basically runs from the 'cloud'). Google offers quite a bit of customization regarding installation. Normally, the notification appears in an iframe, as the first child of <body>. But this can be changed to any location on your page (or it can just float over your page content). The iframe by default contains http://google.com/chromeframe, which includes the download link. You can replace this with your own custom download page. You can also set a destination/thank-you url for post installation. Or, you can replace the entire interactivity that occurs when the plug-in is missing (instead of an iframe appearing, you can make other things happen through JavaScript). Or you can avoid plug-in detection altogether. One interesting thing to note is that, since Chrome Frame basically runs Chrome browser technology, the installation will be immediate ('activate', instead of 'install') if the page visitor already has Chrome installed on their computer. Also, the installation bypasses admin privileges, which mean it can be installed even if the visitor has restricted access to his/her computer. Once Google Frame is installed, it works automatically for any pages in the future. CSS3 Pie PIE consists of 2 main files: PIE.htc and PIE.js (there is also a PIE.php file to be used if you have trouble configuring your server to use the htc file; see the use-note below, in the htc example). In the most basic use of PIE, you only need the htc file, but you can also use the js file instead. What's the difference? While the javaScript is a touch slower and needs a bit more code, it also allows for things like cross-domain code and single header calls. Once installed, it's really simple to use. All you need, basically, is an extra line of code after your normal CSS3 styling. For example, if you have this code (to apply rounded corners to an element): #myElement { -moz-border-radius: 1em; -webkit-border-radius: 1em; border-radius: 1em; }

Page 4


For the htc method, all you need to do is add behavior: url(PIE.htc); to the css in question and the rounded corners will also work on IE6, 7, or 8! #myElement { -moz-border-radius: 1em; -webkit-border-radius: 1em; border-radius: 1em; behavior: url(path/to/PIE.htc); }

Use-note: If for some reason you can't run the htc file in your server, you can use PIE.php to get past this hurdle. To use it, simply make sure both PIE.php and PIE.htc are in the same directory, and then in your CSS point the behavior to the PHP file instead: #myElement { -moz-border-radius: 1em; -webkit-border-radius: 1em; border-radius: 1em; behavior: url(path/to/PIE.php); }

As an alternative to the htc/php method, if you want to use the JavaScript method, you first need to call the js file in the header: <script type="text/javascript" src="path/to/PIE.js"></script>

... and then you use function to plug it into the css: $(function() { $('#myElement').each(function() { PIE.attach(this); }); });

CSS3 CREATION

Sass and Compass Sass: An open-source CSS meta-framework (or 'authoring framework': a layer of easy-to-write code that creates CSS3 auto-magically, and it's CSS3 that is perfectly written- taking into account odd IE bugs etc) There are two syntaxes available for Sass: • The first, known as SCSS ('Sassy CSS'). SCSS understands most CSS hacks and vendor-specific syntax, such as IE’s old filter syntax. • The second and older syntax, known as the indented syntax (or sometimes just “Sass”), simply provides a more concise way of writing CSS. In addition, Sass supports a small set of extensions called SassScript (allows properties to use variables, arithmetic, and extra functions). http://sass-lang.com

Page 5


Compass is a nice, powerful, easy-to-use version/extension of Sass. It leverages the powerful basics of Sass CSS3-creation, in a clean, simple interface. http://compass-style.org

What's available in basic Sass Here we have an example of Compass code: @import "compass/css3"; $background-color: #446688; $foreground-color: lighten(complement($background-color), 20%); $widget-width: 250px; #container { background-color: $background-color; .widget { @include box-shadow(darken($background-color, 20%)); background-color: $foreground-color; width: $widget-width; } .bordered-widget { $border-width: 2px; @extend .widget; // Fix for the broken box model width: $widget-width - $border-width; border: $border-width solid lighten($background-color, 20%); } }

Which is transformed into this CSS code: #container { background-color: #446688; } #container .widget, #container .bordered-widget { -moz-box-shadow: #223344 1px 1px 5px; -webkit-box-shadow: #223344 1px 1px 5px; -o-box-shadow: #223344 1px 1px 5px; box-shadow: #223344 1px 1px 5px; background-color: #bb9977; width: 250px; } #container .bordered-widget { width: 248px; border: 2px solid #7799bb; }

Notice how clean this is. One single #container is output to the 4 necessary css #container calls. And, notice that definitions, such as width in this example, can be defined through relationships (here, the width of .bordered-widget is equal to the width of .widget minus the width of the border). This is done through the use of variables (any selector starting with a $, which simultaneously defines the selector AND sets it as a variable for use in the Compass code).

Page 6


Also, one single box-shadow call is transformed into the 4 box-shadow calls for Mozilla, Webkit, Opera, and 'default' (the @include brings all 4 in together, from a predefined @mixin). A @mixin is basically a small function that outputs chunks of styles that are logically bundled together. In this example, boxshadow @mixin was predefined at some earlier point and looks like this: @mixin box-shadow($definition) { -moz-box-shadow: $ definition; -ms- box-shadow: $ definition; -webkit-box-shadow: $ definition; -o-box-shadow: $ definition; box-shadow: $ definition; }

Where @mixins are too general, and to avoid making redundant copies of @mixins, you can use selector inheritance. Basically, you can use @extend, to create base shared style sets that you can easily add on to. For example: .rounded { border-radius: 5px; border: 1px solid #ccc; } .widget { @extend .rounded; border-color: blue; } .bright-widget { @extend .widget; border-color: #9999ff; }

... will create this CSS: .rounded, .widget, .bright-widget { border-radius: 5px; border: 1px solid #ccc; } .widget, .bright-widget { border-color: blue; } .bright-widget { border-color: #9999ff; }

Sass also offers interesting color rules that make it possible to build complex color themes in a few steps. Among these, you can have Sass mix 2 colors, darken or lighten a color, and derive a color based on the transparency level of another: mix(red,blue) = #7f007f lighten(red,10%) = #ff3333 darken(red,10%) = #cc0000 desaturate(red,10%) = #f20d0d saturate(red,10%) = #5a0c0c fade-out(red,0.25) = rgba(255,0,0,0.75) fade-in(red,0.25) = rgba(255,0,0,0.25) transparentize(red,0.25) = rgba(255,0,0,0.75) grayscale(red) = #808080 complement(red) = #00ffff

Page 7


Sass can also perform mathematical functions, such as: $em-ratio: 1em / 12px; .column { width: 400px * $em-ratio; }

Other ways Sass makes life easy: • You can write comments that won't show in the CSS file (any line starting with // ) • You can choose 4 different ways to output CSS: expanded: the full css, everything on its own full line nested: with indentation for easy reading compact: each style fully on a single line compressed: everything on one single line of code

You can work on partial Sass files (many Sass files that come together before output to CSS):

• •

You can debug your Sass file with the FireSass extension for Firebug. You can change code format from curly braces + semi-colons, to line breaks + indentation.

Name any partial files starting with an underscore (so they will not become CSS) Import partial files into master Sass file with @import

What Compass adds to Sass • The complete Blueprint Framework as mixins instead of ugly class names. www.blueprintcss.org

Dozens of plug-ins you can use, including plug-ins for popular frameworks such as:

• • • •

Project templates to get you up and running quickly with the framework of your choice. Battle-tested cross browser utilities. CSS3 library. Helper functions that make advanced techniques easy; such as image embedding and using asset hosts. Ability to create your own personal framework to share across projects. Mix and match CSS Frameworks with relative ease. Only use the parts of frameworks that you need. Sprites – generated from simple images, with your style sheets dictating how they are constructed.

• • • •

960.gs Susy OOCSS HTML5 Boilerplate

Installation Both Sass and Compass are installed through the RubyGems part of Ruby on Rails. So if you don't have it: • Download from the Ruby on Rails download page •

http://rubyonrails.org/download

Verify that you have RubyGems, typing this command in the command-line interface: gem -v

I actually recommend that you use Handlino's very-easy Compass graphic user interface. It allows you to use Sass without resorting to command line interface. Another bonus: It's written in Java (JRuby), so you don't have to install Ruby (ignore installation instructions above). http://compass.handlino.com

Page 8


USEFUL LINKS

CSS3.info HTML5ROCKS Video: HTML5 Today with Google Chrome Frame 20 Best CSS Frameworks for Developers

Page 9


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.