6
.net CSS3 40 .net december 2010 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 everyone’s 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 Flash’s 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, CSS3- based 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 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 Amaze with CSS3 animations Download the fi les! > All the files you need can be found at www.netmag.co.uk/ tut/ani-209.zip 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 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 browser’s JavaScript engine, or the Flash plug-in, for rendering animations, and they’re 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 O’Brien, 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.” NET209.f_animation 40 10/21/10 1:22:00 PM

net CSS3docshare04.docshare.tips/files/7776/77766744.pdf · .net CSS3 40 .net december 2010 Since the birth of the internet, battles have raged online. Vendors have argued about

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: net CSS3docshare04.docshare.tips/files/7776/77766744.pdf · .net CSS3 40 .net december 2010 Since the birth of the internet, battles have raged online. Vendors have argued about

.net CSS3

40 .net december 2010

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 everyone’s 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 Flash’s 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, CSS3-based 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

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

Amaze with CSS3 animations animations

Download the fi les! >All the fi les you need

can be found at

www.netmag.co.uk/

tut/ani-209.zip

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

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 browser’s JavaScript engine, or the Flash plug-in, for rendering animations, and they’re 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 O’Brien, 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.”

NET209.f_animation 40 10/21/10 1:22:00 PM

Page 2: net CSS3docshare04.docshare.tips/files/7776/77766744.pdf · .net CSS3 40 .net december 2010 Since the birth of the internet, battles have raged online. Vendors have argued about

.net CSS3

.net december 2010 41 next>

NET209.f_animation 41 10/21/10 1:22:01 PM

Page 3: net CSS3docshare04.docshare.tips/files/7776/77766744.pdf · .net CSS3 40 .net december 2010 Since the birth of the internet, battles have raged online. Vendors have argued about

.net xxxxxxxxxxxxxxxx

<prev 42 .net december 2010

.net december 2010 43 next>

Tom Wittlin, head of digital at Folk (wearefolk.com) foresees a creative

explosion, but one that won’t 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 there’s no plug-in, code will adhere to standards and content will be accessible and indexed by search engines.”

There’s another benefit, in that CSS3 could provide smaller teams with more scope when it comes to design. They could use technology they’re 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 you’re building the front-end of a site, you’re 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 animationsIt’s important to learn to use transitions and animations effectively, and to recognise and

understand important building blocks. “With CSS3 animation, we’re really talking about two parts of the same specification,” explains O’Brien. 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 element’s 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; }

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

“Animation and motion catch your eye. Boring text doesn’t,” 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 there’s no JavaScript required.”

Fuchs says the animation works really well in Chrome, and even better in Safari, where

it’s 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 Fuchs’s article ‘Creating Awesome CSS3 Animations’ at mir.aculo.us/2010/08/27/creating-awesome-css3-animations.

Technique Animate a sign-up page

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

Thomas Fuchs

Job title Co-founder Company Slash7 URL slash7.com/company

Right Designer Jason O’Brien is looking forward

to a plug-in-free future Far right Sencha’s banners experiment at dev.sencha.

com/deploy/css3-ads offers CSS3-based ads that are

every bit as good as their Flash counterparts

.net CSS3

NET209.f_animation 42 10/21/10 1:22:04 PM

Page 4: net CSS3docshare04.docshare.tips/files/7776/77766744.pdf · .net CSS3 40 .net december 2010 Since the birth of the internet, battles have raged online. Vendors have argued about

.net december 2010 43 next>

.net CSS3

“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 O’Brien. Designer Faruk Ate (farukat.es) chips in here, noting that “animations work best when GPU-accelerated, which WebKit only does for opacity and -webkit-transform.” He suggests transform: translate() for movement rather than directional properties.

For beginners letting the browser do all the work is tempting, but O’Brien 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 O’Brien. WebKit is currently the only engine supporting such animations, hence the lack of other vendor prefixes in the example.

Future-proofing animationsThe 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 it’s becoming

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

@media screen and (max-width: 940px) { header {width:500px;} }

By adding the following code to the header style, it will animate its width over one second:

header { -webkit-transition: 1s linear width; -moz-transition: 1s linear width; -o-transition: 1s linear width; transition: 1s linear width; }

This effect is less jarring than an element snapping to a new size during a change in window size, so it looks good and enhances usability.

On :targetA more direct use-case relates to the :target pseudo-element. “Many websites use in-page anchors, taking you to an element part-way down a page thanks to a unique id or name attribute,” says Opera Software’s Daniel Davis (people.opera.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 element’s background is lime by default, but magenta if reached via :target:

#my_element { background: #1df914; /* Electric lime */

commonplace to browse on devices that don’t support :hover,” he points out. He hopes designers won’t abuse CSS3 transitions (by only revealing content on hover, for example).

Instead, we should focus on improving usability in a manner that resonates with the user and assists them with a site, regardless of their preferred device. “It’s essential to consider how the user experience is affected when adding animations,” argues Trent Walton, founder of Paravel (paravelinc.com). “Motion demands attention, so if you’re animating unimportant page elements, you may confuse users.” A more positive use for animation is in helping a user understand a transition; here, a site’s entire container can be a candidate for animation. “A technique that’s gaining traction is animating content widths within responsive layouts,” says O’Brien. Responsive layouts display at varying widths depending on the size of the browser window or device viewport.

A site may change header width using code akin to that in the following block, which says that the header should be 500 pixels wide when the browser window is less than 940 pixels:

.net december 2010 43 next>

When working on apps.wikihow.com/survivalkit, Ryan ran into CSS3 animation limitations. “Some properties animate better than others: margin-left isn’t as smooth as left, which is less smooth than transform: translate,” he says. “The best animations are done via transform because it’s 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 they’re 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 don’t specify a property to look for, the function will return the longest duration it finds.” If a property is specified but the element doesn’t have a duration for it, the function returns 0,

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 couldn’t rely on -webkit-transition-delay, 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 wasn’t firing at the correct time. So we used setTimeout, passing in the value we got back from getElementTransitionDuration() to delay the next action.”

Technique Troubleshooting CSS3 animations

Daniel Ryan

Job title Web developer Company Easy Designs URL easy-designs.net

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

“If we all sat on our hands waiting for all browsers to support something, we’d have very numb hands and absolutely no progress” Jason O’Brien

NET209.f_animation 43 10/21/10 1:22:06 PM

Page 5: net CSS3docshare04.docshare.tips/files/7776/77766744.pdf · .net CSS3 40 .net december 2010 Since the birth of the internet, battles have raged online. Vendors have argued about

.netdecember 2010 44 next>

.net CSS3

<prev 44 .net december 2010

} #my_element:target {

background:#ff1dce; /* Hot magenta */ }

“To bring this into the realm of CSS3,” Davis says, “you just add a transition duration to the element’s style.” Updating #my_element as per the following code block provides what Davis calls a “graceful five-second fade from electric lime to hot magenta at the click of a button”:

#my_element { background: #1df914; /* Electric lime */ -webkit-transition-duration: 5s; -moz-transition-duration: 5s; -o-transition-duration: 5s; transition-duration: 5s; }

For browsers that don’t support :target, these styles will simply be ignored, although Davis says you can use media queries to “safely encapsulate styles and effects you only want newer browsers to see”. To demonstrate this, Davis has built a demo with recipe instructions and added media queries to add transitions for modern browsers. Visit people.opera.com/danield/css3/cheesecake with an up-to-date browser; his use of :target and opacity ensures only the currently targeted section is visible. Use an older one and content is displayed linearly. “This avoids the perils of browser-sniffing and ensures content is visible to as many users as possible, but still allows you to have fun with CSS3,” Davis explains.

Automatic animationsNot all online animation requires user interaction, and CSS3 can also help in those scenarios. “One of the best CSS3 demos I’ve seen is Sencha’s ‘CSS3 ads vs Flash ads’,” says Osmani. “Sencha closely

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/

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 they’re “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 ZURB’s 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 absolute-positioned 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;

Greg Rewis

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

Many CSS3 transitions are applied to hover states, but Rewis notes that there are practical applications as well. “Form usability is hit-or-miss, and knowing which field is active can be difficult,” he says. “This can be solved by using a CSS transition to change the background colour and provide a border around the input.”

His technique centres around the pseudo-class :focus, triggered when a user activates a form field, and the CSS3 transition property. “Many browsers provide an outline to focused fields, so that’s removed by setting outline to 0,” Rewis says. “Next, a background and border are added. To draw attention to the change, you can animate the transition between states by adding transition: all .5s to the input rule.” For production sites, also use -webkit, -moz and -o.

“I think textarea elements are some of the most unsightly on the web, but you can style them to match other form elements, only expanding them on focus,” says Rewis. Define a height for textarea in CSS, and then a more desirable height for textarea:focus, removing the default outline and adding the border and background styles applied to the input fields.

“Finally, add the transition, remembering to include vendor-specific prefixes,” says Rewis. The input example transitions all properties, but this one only affects the defined ones:

textarea { height: 20px; transition: height .5s, border .5s, background - color .5s; } 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

Technique Improve your forms

Making a mark Guillermo Esteves’s 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

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

NET209.f_animation 44 10/21/10 1:22:10 PM

Page 6: net CSS3docshare04.docshare.tips/files/7776/77766744.pdf · .net CSS3 40 .net december 2010 Since the birth of the internet, battles have raged online. Vendors have argued about

.netdecember 2010 44 next>

.net december 2010 45

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

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

Technique Build a lightsaber

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

Proceed with cautionInevitably, given the relative immaturity of CSS3 animation, it’s not without problems, both conceptual and technical. Wittlin worries we’ll 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 technology’s 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 O’Brien. “If we all sat on our hands waiting for all browsers to support something, we’d have very numb hands and absolutely no progress.” The caveat he makes is that, since CSS3 animation isn’t fully adopted, you should use it for enhancement or provide elegant fallbacks: “Someone with an older browser shouldn’t know what they’re missing,” he says. “We’re fast approaching a time when browser support won’t be an issue, but you shouldn’t 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

(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 isn’t.” Calzadilla used this technique at hardboiledwebdesign.com.

Going mobileUltimately, 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 Flash’s desktop space, things are more clear-cut on mobile. Flash isn’t 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 don’t go overboard,” he cautions.

Ate is also positive. “As standards advocates, we’ve 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,

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 we’d one day do animation in CSS, the presentational layer.

“I can’t 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 it’s easy to take animations too far and add them superfluously, that’s 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 CSS3

Pa

tric

k La

uke Daniel Davis

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

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 border-radius 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.”

Glowing tribute Daniel Davis’s lightsaber demo showcases a number of CSS3 properties

NET209.f_animation 45 10/21/10 1:22:13 PM