News

A beginners guide to CSS animation

Discover how to get started with animating objects and elements using just CSS

A-beginners-guide-to-CSS-animations

A beginners guide to CSS animations

Everyone remembers the bad old days of Flash; animations took what felt like forever to load and splash pages were often self-indulgent code candy that most users skipped as soon as they could.

Thankfully, the web has moved on significantly since then, with animation almost being a standard feature of many of today’s site designs. Sometimes it’s subtle – a menu that sizes up slightly when you mouse over it, or a button that throbs when you click it. Sometimes it’s a little more extroverted and looks like a controlled page scroll or reveal, or a complicated slider. Then again, sometimes it’s used as an experiment, creating new kinds of user interfaces and experiences.

Whatever the application or end result, animation is a core web skill. When JavaScript ruled the world of web design, animation used to be much more difficult. You had to set up manual animation loops and carefully manage the position, colour and other properties of the objects you were moving around the viewport.

Now with CSS, animation is simpler and far more easily achieved. You tell it exactly when you want it to start, how to stop, what to do and it works automatically. The details are kept locked inside your browser, and you don’t have to worry about them if you don’t want to.

Basic CSS animation, scripted animation, and 3D animation all work differently. There’s some overlap, so you don’t have to learn three completely different skills, but there are differences too. To master animation you’ll have to master them all – the good news is that we’ve made it easy for you. Read on for the details…

Basic building blocks

CSS animation isn’t complicated. You don’t need to use JavaScript or jQuery and you don’t need to be a maths wizard – but you do need to understand a few basics. The essentials are CSS animations, CSS transitions, CSS transforms and event management.
CSS3 animations make it possible to ‘tween’ almost any CSS property. You can either specify ‘from’ and ‘to’ values, or you can split the animation up into keyframes – animation steps – and set the property values for each step. The browser does the rest, working out the intermediate values and changing them over time.
CSS3 2D and 3D transforms are used to move, scale, skew, stretch and otherwise throw elements all around the viewport. Although you can animate many properties, 2D transforms are the basic building blocks of animations that move. 3D transforms do pretty much the same – but obviously with the addition of the third dimension. You can spin, flip, and create perspective effects. While they’re slightly more complicated and difficult to achieve than 2D transforms, they’re much better at grabbing a visitor’s attention.
Finally, you need to trigger and control animations. CSS3 transitions can work with hover and click events. But this is the one part of the process where JavaScript or jQuery can take you further. The usual trick for animations is to create a separate .animated class (you can name it how you want) and use code to add it and remove it in response to user events. Adding a class automatically runs the animations inside it.

CSS3 Animation
w3schools.org has some good basic demonstrations of each different animation option. Visit the page to see some movement.

CSS3 Transitions
Make use of transitions in order to achieve some seamless but simple on-hover and on-click animations to engage your site visitors.

CSS3 2D Transforms
Use 2D transforms to spin, grow, squash, and expand elements. You can also use the skew transform to warp elements as well.

CSS3 3D Transforms
3D transforms appear to move elements in and out of the screen. But creating non-trivial 3D effects with many elements can be a lot of work.

WHAT MAKES A GOOD ANIMATION?

Everyone has seen sites that look like the inside of someone’s brain in the middle of a migraine. It’s tempting to make everything on your site move just because you can, but animation is a secret sauce and it makes the most impact when it’s been used thoughtfully.

First of all, don’t overdo the attention grabbers. You know those sites that put up a modal survey or subscription dialog just when you’re about to get to the information you want? Don’t do that. Users hate anything that makes them feel like they’re not in control of the browsing experience. It’s the same story with attention-grabbing animations. Use them to hint to users that they can do something they might have missed, not to distract them from what they’re already doing.

You should also make use of animation to highlight context and hint at navigation features. For example, if your site uses a map, you can use an animated sidebar to display useful location information. The sidebar contents change all the time, and the animation can be helpful in reminding users that there’s something new and cool they should see. You can also animate breadcrumbs to highlight information you want users to see on each page, while keeping other navigation options visible. Features that resize automatically are a good way to pack a lot of detail into a limited space, without sacrificing relevance.

Consider telling a story. You can do this literally by animating a cartoon – but that’s more work than most sites need. A story is a way to control how information is revealed and good stories keep users interested because they become curious about what happens next. A popular styling at the moment is the full-page scroll. The ‘story’ suggests that there’s more to read. This kind of scroller is better at keeping user interest than a menu tree, because with a menu system there are no surprises and users are more likely to decide to skip some of the content.

Make it physical. You can bounce objects, squash them, shake them and vibrate them. The maths isn’t complicated and simple physics modelling helps make animations look convincing by imitating mass and inertia. If your standard animations aren’t physically believable, users are going to find them more distracting than rewarding. As an occasional special effect you can also make an object do something believable but surprising, for example, making an image that bobs and floats upwards like a balloon.

MAKE IT MOVE

Understand animation from the ground up with this step-by-step guide

Make a box

We’ll start by growing a box and changing its colour. Make a <div> and give it an id of #box. Add some simple CSS to give it a width and a height, then add couple of lines of animation code to run an animation called ‘animOne’ over five seconds.

001    <!DOCTYPE html>
002    <html>
003    <head>
004    <style> 
005    #box
006    {
007        width:100px;
008        height:100px;
009        background:blue;
010        -webkit-animation:animOne 
5s; /* Chrome, Safari, 
Opera */
011        animation:animOne 5s;
012    }
013    </style>
014    </head>
015    <body>
016    <div id = “box”></div>
017    </body>
018    </html>

Make an animation

To define what animOne does, add WebKit and standard @keyframe definitions – as usual, you have to duplicate the code. from {…} defines the CSS at the start of the animation while to {…} defines the CSS at the end – and that’s all you need. If you’re starting with useful default CSS, you don’t even need from {…} at all.
/* For Chrome, Safari and Opera */

001    @-webkit-keyframes animOne
002    {
003        from {width:0px;
004            height:0px;
005            background:red;}
006        to {width:100px;
007            height:100px;
008            background:blue;}
009    }

/* For everything else */
001    @keyframes animOne
002    {
003        from {width:0px;
004            height:0px;
005            background:red;}
006        to {width:100px;
007            height:100px;
008            background:blue;}
009    }

Run it

Load the page into a browser and the animation should run on load4-anim. That’s about all all there is to know about basic animation. You can animate most CSS. For a detailed list of animatable properties, see oli.jp/2010/css-animatable-properties.

001    #box
002    {
003        width:100px;
004        height:100px;
005        background:blue;
006        -webkit-animation:animOne 
1s; /* Chrome, Safari, 
Opera */
007        -webkit-animation-delay: 2s;
008        -webkit-animation-iteration-
count: 4;
009        -webkit-animation-direction:
alternate;
010        animation:animOne 1s; /* 
The rest… */
011        animation-delay: 2s;
012        animation-iteration-count: 4;
013        animation-direction: 
alternate;
014    }
015    

More control

You can delay the animation and repeat it, or even try playing it in reverse with the animation-direction property. Each forward or back change counts as one iteration. Set the count to infinite if you never want the animation to end. The total running time is the count multiplied by the duration.

001    #box
002    {
003        width:100px;
004        height:100px;
005        background:blue;
006        position: relative;    /* 
Need relative or absolute 
for movement */
007        -webkit-animation:animOne 
1s; /* Chrome, Safari, 
Opera */
008        -webkit-animation-iteration-
count: 4;
009        -webkit-animation-direction:             alternate;
010        animation:animOne 1s;
011        animation-iteration-count: 4;
012        animation-direction: 
alternate;
013    }
014    

/* For Chrome, Safari and Opera */
001    @-webkit-keyframes animOne
002    {
003    0%   {background: red; 
left:0px; top:0px; width: 
100px; height: 100px;}
004    25%  {background: yellow; 
left:200px; top:0px; width: 
0px; height: 0px;}
005    50%  {background: blue; 
left:200px; top:200px; width:
200px; height: 200px;}}
006    75%  {background: green; 
left:0px; top:200px; width: 
0px; height: 0px;}
007    100% {background: red; 
left:0px; top:0px; width: 
100px; height: 100px;}
008    }
009

Break it up

Instead of from/to, you can define animation stages with percentage markers. Add as many as you like, each sets the CSS properties for that step. This gives you a lot more control because you can define movement paths and colour transformations with as much detail as you want.

Run it again

Save the file and load the HTML. You’ll see the square bouncing around the screen and changing colour like crazy. At the end, the animation defaults to the initial properties. If you want it to finish with different values, use animation-fill-mode to set them.

Easings and Beziers

Get ultimate control of positioning and timing with expert-level animation easing management

Smooth moves

We’ll create a simple but non-trivial text animation using motion control. Make a <div> with a single letter in it (this example uses some gratuitous Google font code). Create an animation called animX. To avoid duplication, we only include the WebKit code. Copy it and remove ‘-webkit-‘ to support IE.

001    <!DOCTYPE html>
002    <html>
003    <head>
004    <link rel=”stylesheet”type=”
text/css” media=”all” href=
”//fonts.googleapis.com/
css?family=Lato”/>
005    <style> 
006    #textX
007    {
008        left:100px;
009        top:100px;
010        font-family: “Lato”;
011        font-size: 100px;
012        position: absolute;
013        -webkit-animation:animX 1s; 
/* Chrome, Safari, Opera */
014    }

/* Chrome, Safari, Opera */
001    @-webkit-keyframes animX
002    {
003        from {left:0px;
004            top:0px;}
005        to {left:100px;
006            top:100px;}
007    }
008    </style>
009    </head>
010    <body>
011    <div id = “textX”>X</div>
012    </body>
013    </html>

Straight lines

Run the animation. By default, animations use an in-out motion curve that accelerates into the movement before slowing down. The curve is set using an easing function, which defines how the animated property moves from start to finish. Try replacing the easing function with linear to see how the movement changes.

001    #textX
002    {
003        left:100px;
004        top:100px;
005        font-family: “Lato”;
006        font-size: 100px;
007        position: absolute;
008        -webkit-animation:animX 1s; 
/* Chrome, Safari, Opera */
010        -webkit-animation-timing-
function:linear;
011    }

Crash stop

The two other options are ease-in and ease-out. The first starts slowly and then stops quite suddenly, making it look as though the element has crashed into an invisible wall. The second starts suddenly and stops slowly, as if the element is gliding to a stop. The default ease-in-out uses both to speed up and slow down.

001    #textX
002    {
003        left:100px;
004        top:100px;
005        font-family: “Lato”;
006        font-size: 100px;
007        position: absolute;
008        -webkit-animation:animX 1s; 
/* Chrome, Safari, Opera */
009        -webkit-animation-timing-
function:ease- out; /*  Or 
ease-in */
010    }
011    

Custom curves

What if you want to roll your own easing? You can use the cubic-bezier curve option to define the movement with a series of four numbers. As a demonstration, the numbers in the code copy the ease-in-out curve – but you can change them to create your own custom easing if you like.

001    #textX
002    {
003        left:100px;
004        top:100px;
005        font-family: “Lato”;
006        font-size: 100px;
007        position: absolute;
008        -webkit-animation:animX 1s; 
/* Chrome, Safari, Opera */
009        -webkit-animation-timing-
function:cubic-bezier(0.4, 0
,0.36,0.66);
010    }
011    

Control horizontal and vertical

How do you know what the numbers do? You can experiment with them at random and end up getting utterly confused. Or, you can visit the handy cubic-bezier.com site, which has a cool preview feature with blobs and curvy lines and handles you can drag. Click GO! to preview your custom curve.

001    #textX
002    {
003        left:100px;
004        top:100px;
005        font-family: “Lato”;
006        font-size: 100px;
007        position: absolute;
008        -webkit-animation:animX 1s; 
/* Chrome, Safari, Opera */
009        -webkit-animation-timing-
function:cubic-bezier(0.8, 
1.82 , 0.36, 0.66);
010    }
011    

Bounce effect

With some fancy tweaking and some out of range you can simulate a simple bounce effect. The other way to make a bounce is to use percentage keyframes to move an object past its target position back again. Repeat this a few times with decreasing durations and distances for the smoothest effect.

TOP CSS ANIMATION FRAMEWORKS & RESOURCES

Animate.css

url daneden.github.io/animate.css
A lightweight but powerful collection of ready-to-roll CSS animations, you can download this framework directly from the site or from GitHub, drop into a project, and get instant access to a huge collection of animation effects. The list includes entrances, exits, fades, flips, hinges, and even a few sliders. The code is simple so it’s easy to customise it with your own easings and other additions but for most projects you won’t need to, because the basic effects are so useful right out of the box. Plus, the subtle colour fade on the site looks lovely.

Move.js

url visionmedia.github.io/move.js
Move.js packages a collection of CSS animations and makes them accessible with a few lines of code. Don’t be deceived by the bare site, this is more of a toolkit than Animate.css, so some assembly is required. You can use the animations as is, but things get a lot more interesting with the conditional options. Use them to chain animations together, select animations depending on other events, set up callbacks and customise different easings. The site’s design doesn’t make it obvious that each feature has a demo under it but it does, so check it out.

Anima.js

url lvivski.com/anima
Anima is a combined CSS/JavaScript animation framework with physics support. It handles the usual chained/delayed animation options available in other frameworks, but also includes features that make it easy to squash and bounce items as you animate them. The framework is only 5k, so it’s lightweight enough to add to any project. The only catch is that it’s more of a full animation API than a simple drop-in library of canned effects. You may want to master a less complex framework before trying to use this one on a production project.

Greensock GSAP.js

url www.greensock.com
Making a bid as the next Flash, Greensock’s GSAP.js framework is a fast and efficient HTML5 library for professional animation applications. It’s a streamlined alternative to jQuery animation, optimised for speed and with added timeline management and optional plug-ins. The good news is that it does a lot. It’s much more powerful than plain CSS animation, which has helped it find a home in high-end commercial projects. The bad news? It costs up to $150 per year if you use it in games or subscription sites. Still, basic use is free, so it’s definitely worth a look.

CSS3 Animation Cheat Sheet

www.justinaguilar.com/animations
As the name says, this is a handy cut-out-and-keep cheat sheet of canned CSS3 animations. There’s a collection of buttons, a pile of code and a quirky demo area so you can see what each animation does. There are also some notes about creating more sophisticated effects by linking the animations into jQuery scripts.

Improve your web design skills with Web Designer. Download issues direct from GreatDigitalMags.com or buy print issues from ImagineShop

×