You are on page 1of 6

.

net CSS3

Amaze with CSS3 animations


Words Craig Grannell is a web designer and writer. Check out his creations at snubcommunications.com Image Rob Bowen is art editor of .net and has 13 years experience of working in magazines. twitter.com/speshbob

Download the les! > need u

All the les yo can be found at .uk/ www.netmag.co 09.zip tut/ani-2

As an across-the-board shift towards open standards continues, Craig Grannell asks designers at the cutting edge how best to animate web pages using CSS3
Since the birth of the internet, battles have raged online. Vendors have argued about how elements should be added to pages, proprietary technologies have risen and fallen and standards advocates have tried to bash everyones heads together to figure out how to usher in an era of consistency and openness. A current war centres on animated content, much of which relies on Flash. However, CSS3 is starting to muscle in on Flashs turf, providing designers with in theory a more open way to create web animations and transitions without relying on plug-ins and libraries. As with other nascent technologies, CSS3based animations sit at the bleeding-edge of web design. Live examples (bar experiments) are few in number, and even proponents argue that anyone eager to delve into CSS3 animations should be mindful of the drawbacks. However, those immersed in the field also insist CSS3 animations are something all designers should be excited by.

Get animated
Today, most designers rely on the quality and performance of a browsers JavaScript engine, or the Flash plug-in, for rendering animations, and theyre not always as fast as they need to be, says Addy Osmani, senior UX developer at Shortsaleology. Using CSS3 to achieve similar effects should improve performance and reduce download times. When you remove the reliance on plug-ins, other benefits become clear. Jason OBrien, web designer for the Centresource Interactive Agency (centresource.com), notes that this should lead to a more stable browsing experience for users, and that it results in easier maintenance: You can make changes without the need to export or recompile.

40

.net december 2010

NET209.f_animation 40

10/21/10 1:22:00 PM

.net CSS3

.net december 2010 41

next>

NET209.f_animation 41

10/21/10 1:22:01 PM

.net xxxxxxxxxxxxxxxx CSS3


Right Designer Jason OBrien is looking forward to a plug-in-free future Far right Senchas banners experiment at dev.sencha. com/deploy/css3-ads offers CSS3-based ads that are every bit as good as their Flash counterparts

Tom Wittlin, head of digital at Folk (wearefolk.com) foresees a creative explosion, but one that wont be to the detriment of the accessible web. With CSS3 animations, websites will start to come to life in a similar way to when Flash first arrived on the scene, he says. That began with designers dropping in the odd animation but progressed to animated navigation systems and full-blown interactive experiences. This is bound to happen with CSS3. But since theres no plug-in, code will adhere to standards and content will be accessible and indexed by search engines. Theres another benefit, in that CSS3 could provide smaller teams with more scope when it comes to design. They could use technology theyre familiar with rather than have to work with alien software such as Flash. In this regard, Paul Annett of Supernice Studio (supernicestudio. com) thinks freelancers have a distinct advantage: If youre building the front-end of a site, youre able to design CSS3 behaviour in the browser, as it were, when coding the page. In an agency, where roles are more defined and potentially

rigid, the job of creating CSS3 behaviours sits in the grey area between visual design and front-end development. Without good team communication, it could find itself forgotten about.

Transitions and animations


Its important to learn to use transitions and animations effectively, and to recognise and

Technique Animate a sign-up page Thomas Fuchs


Job title Co-founder Company Slash7 URL slash7.com/company its hardware-accelerated. Apparently, it also fares well on mobile devices. Many people view the site on the iPhone, iPad, Android phones and Palm webOS phones, and you can see the animation just fine, Fuchs says. On iPhones, you actually get 60fps, buttery-smooth performance. Funnily, though, animated GIFs are not supported on Android phones, but CSS animations are. Go figure! For details on the code behind the animation, take a look at Fuchss article Creating Awesome CSS3 Animations at mir.aculo.us/2010/08/27/ creating-awesome-css3-animations.

understand important building blocks. With CSS3 animation, were really talking about two parts of the same specification, explains OBrien. Transitions, he says, are the simpler, more automated form of CSS3 animation, enabling movement between two states. Should you want images to grow when the cursor is over them, say, specify a hover state that uses the transform property and scale value (along with appropriate vendor-specific fallback prefixes), and define a transition in the original elements style [for full sets of properties and values, see w3.org/TR/css3-animations]: img:hover { -webkit-transform: scale(1.2); -moz-transform: scale(1.2); -o-transform: scale(1.2); transform: scale(1.2); } img { -webkit-transition: .5s linear all; -moz-transition: .5s linear all; -o-transition: .5s linear all; transition: .5s linear all; }

Animation and motion catch your eye. Boring text doesnt, says Thomas Fuchs, explaining why Slash7 created an animated cartoon pirate for timebemoney.com, a mini-site that promotes time tracking. Most mailing list sign-ups are boring not ours! Slash7 was keen to create a lightweight implementation that most people who visited the site would see. With no external libraries required, the site loads ultra-fast, Fuchs explains. The majority of our target audience is on Safari or Chrome and will see the animation. After an illustrator provided a vector image, Slash7 coloured and rasterised it, then cut it into pieces, separating the arm and clock handles. We used WebKit to animate the clock handles and arm, and threw in an old-school animated GIF to make the eye blink, explains Fuchs. Now, when you visit the site, Captain Track greets you, waving his freelancing treasure map, and theres no JavaScript required. Fuchs says the animation works really well in Chrome, and even better in Safari, where

Attention grabbing An animated Captain Track gives a jolly welcome to freelancers at timebemoney.com

Pros and cons Marco Kuipers posters (demo.marcofolio. net/3d_animation_css3) showcase CSS3 animation but also highlight browser issues the Tron text flickers in Safari

<prev

42

.net december 2010

NET209.f_animation 42

10/21/10 1:22:04 PM

.net CSS3
Technique Troubleshooting CSS3 animations Daniel Ryan
Job title Web developer Company Easy Designs URL easy-designs.net so you always have an integer value to use in things like setTimeout. To see this in action, see apps.wikihow.com/survivalkit/#/categories. To get the cards to slide out from the centre one at a time, we couldnt rely on -webkit-transitiondelay, since each card would need a different delay and we potentially have dozens of cards to work with. The right thing would be to trigger the next card to move by attaching an event to transitionEnd, but in practice, that event wasnt firing at the correct time. So we used setTimeout, passing in the value we got back from getElementTransitionDuration() to delay the next action.

Truck trick The contact section at bountybev.com includes a lorry that drives off to reveal a link; in non-WebKit browsers it degrades with a more basic jump

The all attribute transitions differences between the normal and hover states. If you also specified top: -10px; it would animate the position as well as the scale, says OBrien. Designer Faruk Ate (farukat.es) chips in here, noting that animations work best when GPU-accelerated, which WebKit only does for opacity and -webkittransform. He suggests transform: translate() for movement rather than directional properties. For beginners letting the browser do all the work is tempting, but OBrien thinks the animation part of the spec is the real powerhouse: You specify steps and set properties for each keyframe. In the previous example, you could add a bounce when the cursor is placed over an image: img:hover { -webkit-animation: grow .5s 1; } @-webkit-keyframes grow { 0%{-webkit-transform:scale(1);} 30%{-webkit-transform:scale(1);} 50%{-webkit-transform:scale(1.5);} 60%{-webkit-transform:scale(1.2);} 100%{-webkit-transform:scale(1.2);} } In the additional img:hover rule, the animation is defined to happen over half a second and only once. By setting a keyframe where we animate the scale up to 1.5 and then right back down to 1.2, we get a nice bump-easing effect instead of a linear transition, adds OBrien. WebKit is currently the only engine supporting such animations, hence the lack of other vendor prefixes in the example.

When working on apps.wikihow.com/survivalkit, Ryan ran into CSS3 animation limitations. Some properties animate better than others: marginleft isnt as smooth as left, which is less smooth than transform: translate, he says. The best animations are done via transform because its hardware-accelerated in most browsers. Another roadblock he found was matching animation timings to JavaScript events. In theory, you could attach event handlers to transitionStart and transitionEnd, but theyre buggy, often firing at the same time, says Ryan. He therefore created a function, getElementTransitionDuration, to assist, available via gist.github.com/589133. Different properties can have different durations, so we must match the property we want to its duration, he explains. If you dont specify a property to look for, the function will return the longest duration it finds. If a property is specified but the element doesnt have a duration for it, the function returns 0,

Wild ride The wikiHow survival app employs CSS3 animation but had its fair share of development issues

Future-proofing animations
The majority of CSS3 animations are hover-based, subtly adding polish and usability to websites on the desktop, but Annett warns us not to become enamoured or reliant on that situation. Although hover effects are tempting, the technology is emerging at the same time that its becoming

If we all sat on our hands waiting for all browsers to support something, wed have very numb hands and absolutely no progress
Jason OBrien

commonplace to browse on devices that dont @media screen and (max-width: 940px) { support :hover, he points out. He hopes designers header {width:500px;} .net december 2010 43 next> wont abuse CSS3 transitions (by only revealing } content on hover, for example). Instead, we should focus on improving By adding the following code to the header usability in a manner that resonates with the style, it will animate its width over one second: user and assists them with a site, regardless of header { their preferred device. Its essential to consider how the user experience is affected when adding -webkit-transition: 1s linear width; animations, argues Trent Walton, founder of -moz-transition: 1s linear width; Paravel (paravelinc.com). Motion demands -o-transition: 1s linear width; attention, so if youre animating unimportant page transition: 1s linear width; elements, you may confuse users. A more positive } use for animation is in helping a user understand a transition; here, a sites entire container can be This effect is less jarring than an element snapping a candidate for animation. A technique thats to a new size during a change in window size, so it gaining traction is animating content widths within looks good and enhances usability. responsive layouts, says OBrien. Responsive On :target layouts display at varying widths depending on the A more direct use-case relates to the :target size of the browser window or device viewport. pseudo-element. Many websites use in-page A site may change header width using code anchors, taking you to an element part-way down akin to that in the following block, which says that a page thanks to a unique id or name attribute, the header should be 500 pixels wide when the says Opera Softwares Daniel Davis (people.opera. browser window is less than 940 pixels: com/danield). This is a target and is prefixed in the URL by a hash symbol. If the target element has a specified id value, you can apply styles to it and use :target to define styles that are only applied when the user arrives at an element by clicking a targeted link. Here, the elements background is lime by default, but magenta if reached via :target: #my_element { background: #1df914; /* Electric lime */

.net december 2010 43

next>

NET209.f_animation 43

10/21/10 1:22:06 PM

.net CSS3

Right Tom Wittlin reckons CSS3 will lead to an explosion of design creativity Far right 3D rotating cube navigation at paulrhayes. com/experiments/cube-3d/

Technique Improve your forms Greg Rewis


Job title Principal evangelist Company Web Tools, Adobe Systems, Inc. URL blog.assorted garbage.com

With CSS3 animations, sites will start to come to life in a similar way to when Flash rst arrived on the scene
Tom Wittlin

} #my_element:target { background:#ff1dce; /* Hot magenta */ }

Many CSS3 transitions are applied to hover To bring this into the realm of CSS3, Davis states, but Rewis notes that there are practical says, you just add a transition duration to the applications as well. Form usability is hit-orelements style. Updating #my_element as per the miss, and knowing which field is active can be following code block provides what Davis calls a difficult, he says. This can be solved by using a graceful five-second fade from electric lime to hot CSS transition to change the background colour magenta at the click of a button: and provide a border around the input. His technique centres around the pseudo#my_element { class :focus, triggered when a user activates a background: #1df914; /* Electric lime */ form field, and the CSS3 transition property. -webkit-transition-duration: 5s; Many browsers provide an outline to focused -moz-transition-duration: 5s; fields, so thats removed by setting outline to -o-transition-duration: 5s; 0, Rewis says. Next, a background and border transition-duration: 5s; are added. To draw attention to the change, you } rebmeced ten. can animate the transition between states by >txen For browsers that dont support :target, these 44 0102 adding transition: all .5s to the input rule. For production sites, also use -webkit, -moz and -o. styles will simply be ignored, although Davis says I think textarea elements are some of the you can use media queries to safely encapsulate most unsightly on the web, but you can style styles and effects you only want newer browsers to them to match other form elements, only see. To demonstrate this, Davis has built a demo expanding them on focus, says Rewis. Define with recipe instructions and added media queries a height for textarea in CSS, and then a more to add transitions for modern browsers. Visit desirable height for textarea:focus, removing people.opera.com/danield/css3/cheesecake with an the default outline and adding the border and up-to-date browser; his use of :target and opacity background styles applied to the input fields. ensures only the currently targeted section is Finally, add the transition, remembering to visible. Use an older one and content is displayed include vendor-specific prefixes, says Rewis. The linearly. This avoids the perils of browser-sniffing input example transitions all properties, but this and ensures content is visible to as many users one only affects the defined ones: as possible, but still allows you to have fun with CSS3, Davis explains. textarea { Automatic animations height: 20px; Not all online animation requires user interaction, transition: height .5s, border .5s, background and CSS3 can also help in those scenarios. One color .5s; of the best CSS3 demos Ive seen is Senchas CSS3 } ads vs Flash ads, says Osmani. Sencha closely textarea:focus { outline: 0; height: 250px; background-color: rgb(246,255,100); border: rgba(72, 107, 11, .7) 9px solid; border-radius: 6px; } Check out the demo for yourself at www. netmag.co.uk/tut/ani-209.zip

replicated some Flash ads in CSS3, and although the demo is WebKit-specific, you can already see the lines blurring between what Flash and CSS3 can achieve. The examples are online at dev. sencha.com/deploy/css3-ads, but Osmani notes that animations can also be used for subtler effects, including CSS3 replacements for loading animations, instead of using animated GIFs. ZURB is well known for CSS3 experiments, and while designer Jonathan Smiley comments that you can use CSS3 animations for things ranging from the subtle to the horrendously annoying, he thinks theyre great for repeating effects or anything that needs to loop. He adds that such animations can also be triggered by JavaScript. Interesting examples include the animated private eye at hardboiledwebdesign.com, a scrolling star-field at paulrhayes.com/experiments/parallax and ZURBs own radioactive buttons at zurb.com/playground/ radioactive-buttons, where looping animations cycle button background and box-shadow colours to make them glow. Smiley says ZURB uses WebKit to test concepts in verifyapp.com prior to switching to jQuery: In label tests, a pulse appears to show where users are expected to label, and the code is a mix of animation, CSS3 transforms and a PNG image. An example of such a page is available at verifyapp.com/l/1908. Each pulse is an absolutepositioned element with the pulse PNG defined as its background. Keyframing is used to change the scale and opacity of relevant elements: @-webkit-keyframes pulse { from { -webkit-transform: scale(0.0); opacity: 0; } 10% { -webkit-transform: scale(0.1); opacity: 1;

Making a mark Guillermo Estevess take on the Star Wars opening text crawl (gesteves.com/experiments/starwars.html) is a CSS3 legend. But designers are now moving beyond proof of concept demos to using CSS3 in their daily client work

<prev

44

.net december 2010

NET209.f_animation 44

10/21/10 1:22:10 PM

.net CSS3
Technique Build a lightsaber
Patrick Lauke

Daniel Davis
Job title Web evangelist Company Opera Software URL people.opera.com/ danield

Get started Our demo (www.netmag.co.uk/tut/ani-209.zip) showcases some basic components of CSS3 animation

} 90% { -webkit-transform: scale(0.9); opacity: 0.1; } to { -webkit-transform: scale(1); opacity: 0; } }

Proceed with caution


Inevitably, given the relative immaturity of CSS3 animation, its not without problems, both conceptual and technical. Wittlin worries well see a standards-compliant repeat of when Flash was abused to the max, with nasty, lengthy splash intros, annoying sound effects and functionless animated graphics. Daniel Ryan, web developer for Easy Designs (easy-reader.net), bemoans the technologys current state. CSS3 animations still need improving, he says. Try stacking different transforms onto an element or getting access to the timing of a particular type of transition via JavaScript to find out why! Developer Tim Murtaugh (timmurtaugh.com) also reckons the implementation is imperfect. When triggered, some animations cause unrelated elements on the page to flicker or stutter in Safari, he says. Some people complain CSS3 animation makes you design for one browser engine (WebKit), or forces the use of proprietary vendor-specific prefixes. This is bollocks, counters OBrien. If we all sat on our hands waiting for all browsers to support something, wed have very numb hands and absolutely no progress. The caveat he makes is that, since CSS3 animation isnt fully adopted, you should use it for enhancement or provide elegant fallbacks: Someone with an older browser shouldnt know what theyre missing, he says. Were fast approaching a time when browser support wont be an issue, but you shouldnt deliver a bad experience to anyone. So when using animations, ask how they enhance the experience. Another possibility, proposed by CSS3 experimenter Anthony Calzadilla (www. anthonycalzadilla.com), is to bring lagging browsers up to speed. You can use Modernizr

Going loopy Anthony Calzadillas I Twitty The Fool! (anthonycalzadilla.com/i-twitty-the-fool) features looped animation thats reminiscent of Flash content

Davis hacked together a lightsaber demo (people.opera.com/danield/css3/lightsaber) to experiment with CSS3 animations. The result showcases several properties, and shows how JavaScript can enhance projects. I started with a static lightsaber a couple of divs and icons for the controls, he says. The blade and handle have repeated background images and fixed widths and heights. The blade also uses borderradius and box-shadow for the glow effect. I then created styles for the active and inactive states, using the CSS3 transform property as well as scale, translate and rotate values, remembering to include vendor prefixes. With JavaScript, Davis set click and mouseover event listeners to the buttons: These trigger functions that play audio and change the class names of the buttons and lightsaber. When the class names change, the new CSS values take effect, resulting in a change of appearance. The animation was made by adding a transition-duration property to the lightsaber and buttons. Whenever any of their CSS values change, they animate over a set period of time, in this case half a second.

(modernizr.com) for fallback styles and animation, and even the Modernizr JavaScript object to detect whether CSS3 animation is available, providing jQuery animation if it isnt. Calzadilla used this technique at hardboiledwebdesign.com.

Going mobile
Ultimately, the important thing is to move forward by enhancing sites now, you can stand out. Smiley thinks smooth transitions using CSS3 animations make a browsing experience feel more polished, like when you first experienced a professionally built Flash site. He adds that, while CSS3 is making a play for a chunk of Flashs desktop space, things are more clear-cut on mobile. Flash isnt on iOS and is problematic on Android, but with most mobile platforms using WebKit browsers, CSS3 and JavaScript can replicate much of what Flash would have been used for. Of course, processor capability is a factor, so dont go overboard, he cautions. Ate is also positive. As standards advocates, weve worked long and hard to educate web developers about the importance of separation of structure, presentation and behaviour, so it surprises me that some of these people voice their disagreement with new technologies like CSS3 transitions and animations, he says. Previously, such tasks required a lot of JavaScript or a plug-in,

Glowing tribute Daniel Daviss lightsaber demo showcases a number of CSS3 properties

whereas CSS3 allows us to take the most clean, semantic base and add life and interactivity more easily than ever before. He argues that much animation on the web is presentational, so it was an almost inescapable conclusion that wed one day do animation in CSS, the presentational layer. I cant work on a website without thinking how and where I could add some transitions to make it feel more alive and fun, he says. While its easy to take animations too far and add them superfluously, thats not a reason to not get excited about CSS3 animations. More simple and easy control over user interfaces is a good thing. Problems with CSS transitions and animations? Ask for help at forum.netmag.co.uk.

.net december 2010 45

NET209.f_animation 45

10/21/10 1:22:13 PM

You might also like