Practical CSS3 Animations

This was the talk I gave for Reasons To Be Creative, September 4, 2012. Slides and transcript below.

(slide2)

How’s everyone enjoying Reasons so far? I’ve seen some really fantastic talks these past couple of days, it’s going to be hard to follow them!

So for the last couple of weeks, I’ve had a bad ear infection that’s left me half deaf, so if you’re going to shout insults to me – please make sure you shout them extra loud so I can hear them properly.

(slide3)

If you don’t know me, my name is Amber Weinberg and I’m a freelance front-end developer. I spend my days doing the cool stuff like developing for mobile and creating badass WordPress themes. I’ve been coding since I was 12 years old, and 14 years later, here I am, in front of you wonderful people talking about what I do best – CSS.

Before we get going, I wanted to let you know that the slides and code will be available on slide share, as well as the transcript on my own site, so you don’t have to worry about taking lots of notes.

So let’s get started. Who here loves using CSS3.

(slide4)

We’re all familiar with a bunch of interesting new features in CSS3. Most of us know how to use things like border radius, RGBa and even some of the advanced selectors. But I’ve noticed that a lot of us are still struggling with understanding animations and image manipulations. Most likely this is due to the fact that this area of CSS3 is the most radically different from standard CSS syntax.

(slide5)

Don’t freak out – this isn’t about Internet Explorer!

Most of us are familiar with some really cool experiments where the developers have taken a popular logo or social media icon and completely recreated it using only CSS.

(slide6)

What makes this type of thing impractical? Check out the CSS for this. For one logo. Nuff said, right?!

(slide7)

Or perhaps you’ve seen Anthony Calzadilla’s fantastically awesome Spiderman comic, that’s done completely in CSS3?

(slide8)

Well not to be a killjoy but….this is not what I’m going to teach you how to do today.

(slide9)

Instead, I’m going to talk about some practical uses of CSS3 animations, transitions and transforms. You know, something you can use for almost any client.

While animating comics and recreating logos in CSS3 show just how powerful it can be, it’s not really useful or cost effective for actual productions. I’m going to show you some smaller animations that are super quick to implement and give just the right amount of movement. I’ll first teach you the basics of CSS3 transitions, transforms and animations. Then, I’ll show you some examples of animations I’ve used for my own clients, to give you a taste of just what can be done.

(slide10)

Why should you care about CSS3 animations? Using CSS3 animations can give life to a plain website and bring an unexpected, but pleasant surprise to the visitor. Also, instead of using Javascript, CSS3 downloads faster and isn’t dependant on an outside library or having scripting turned on. Eventually, when browser support becomes wide enough, CSS3 will most likely replace a lot of Javascript that we’d normally use today. I’ve seen some great examples of sliders, fading slideshows and other animations that were completely done in CSS – so it’s going to be interesting to see just what we can do in the future!

Ready? Let’s get started!

(slide11)

Here’s an example of all three animation types. I know this looks like a bunch of jumbled crap, but I promise it’s actually pretty damn cool. We’re going to cover the basic syntaxes of CSS3’s transitions, transforms and animations properties first and then dive into a couple of real world examples.

As you can see – these are quite different that the basic CSS properties that you are used to and can be quite confusing upon first glance!

(slide12)

CSS3 transitions are the easiest of the three to understand, so let’s start there. Transitions are used to change a property’s value. This can be anything from the background colour, a text colour, opacity or even positioning.

Most of the time, transitions are used for rollovers and controlling the speed and ease of the change between one value to the next. Let’s take a closer look at the previous example to see what makes up the syntax.

(slide13)

The syntax for transitions is pretty easy to understand once you figure out the basics. The first value will be the property you want to change. In this example, you’re going to be changing the CSS3 property ‘colour’. This could also be ‘opacity’ if you wanted to change the opacity of the item, or background-colour, or you could even use the word ‘all’, which transitions all of the properties that changed from regular to hover state.

The next value is the speed of the transitions in seconds, so for this example, 1s is 1 second.

The last value is the transition effect. CSS3 transitions takes all of the basic effects, like ease, ease-in, linear etc etc. If you’ve got some jQuery experience, then these should be pretty familiar to you because they’re exactly the same. There’s no fast rule for using effects and you’ll just have to play around with them to decide which looks best for the animation you’re creating.

(slide14)

Here’s a nice example of transition on an actual element. We’ve set a link element to have an ugly grey background with black text. When rolling over the link, you can see instead of flipping over quickly to the hover values of a black background and white text, the button nicely fades or ‘transitions’ into the new values.

We give the transition a value of “all (which means every changed element will transition)” to be completed in 1 second with an ease effect.

Transitions alone are pretty badass, but let’s move on to the new property: transforms!

(slide15)

By themselves, transforms don’t really perform anything animated. Instead, they manipulate the element itself. You can rotate, skew, move (called translate) or scale up and down. This can be done either on actual HTML elements, like divs, paragraphs, etc, or on images themselves.

(slide16)

The syntax for transforms are pretty easy, although there are multiple rules you can use to fine-tune your transforms.

Transform is what you use to tell CSS how to change the property. You simply state the type of transform you wish to perform, in this example, it’s rotate, and then how far you wish to perform it in degrees. You could also decide to only transform on one or the other axis, by specifying with an X or a Y after the transform type. So your rule would then be transform skew-x or rotate-y if you were wanting to rotate it on one axis only.

Transform origin is an optional property that tells CSS where to transform from, in the current example 0,0 means to start from the top left corner. This works on a basic x,y axis. The default value is the very centre of the property.

(slide17)

Here’s  some examples of basic transforms. Note that unlike the previous example, there’s no animation to these by themselves, but you could put them on a hover to animate – or use them in conjunction with transitions and animations, which we’ll cover in a bit.

The first example shows the div just by itself – it’s a plain 200 by 200 square.

The green example shows what happens when we apply a rotate transform of 30 degrees. The square simply rotates 30 degrees clockwise.

The red example shows what happens when we decide to skew it by 30 degrees instead – the element (in this case a div, but it could also be an image) distorts itself.

(slide18)

If we combine both transitions and transforms together, on a hover event – we might get something like what you see on the screen. I’ve simply told CSS to rotate the box all the way around on hover, and it performs the transition quite smoothly!

This is where we can start to make some pretty complicated and interesting events.

(slide19)

We can even add in multiple transforms, transitions and properties!

This box not only rotates all the way around on hover, but also scales up to double it’s original size. Notice how none of these properties are happening abruptly, but instead are “transitioning” smoothly;

This is just too much fun, but let’s move on to the most confusing of the three properties – CSS3 animation!

(slide20)

Animations are a bit trickier to code than Transforms and Transitions because it requires the use of several new rules.

The difference between animations and transitions, is that animations are meant to actually move items. While you can technically move an element with transitions, you can’t really fine tune the move or timing nor have it move in more than one direction at a time. Animations works similar to something like Flash timelines, but is much simpler to use, works on mobile devices and doesn’t require 3rd party software.

(slide21)

We first need to create a set of keyframes that tell CSS what we want our animation to do and when to do it. If you’re familiar with animation programs like Adobe Flash, you’ll recognise what keyframes are, but if you’re not, they’re basically points in the timeline of the animation.

In our example above, we’ve created a set of keyframes that tell CSS that we want our element to start with a left of 0, then in the exact middle of the animation, we want our element to move left by 50px, and then at the very end of the animation, we want the element to return back to a left of 0. Notice that the keyframe uses percentages to mark the points on the timeline.

Each set of keyframes needs to be given a name that we can reference in the actual element. In this example, we’ve named the animation ‘slide’. You can see that once we get to the actual element, we reference the “slide” keyframes in the animation name property. We then tell CSS that we want our animation to last 2 seconds and to repeat itself 3 times.

Animation direction seems a bit more complicated at first, but it’s quite easy once you understand what it does. It tells CSS how it wants the animation repeated. Alternate means the animation will run from start to finish, then from finish to start again. If we were to give animation direction a normal setting (or left it out altogether) the animation would proceed from start to finish, then jump back to start and go to finish again. We’ll see how alternate works soon.

(slide22)

For this example, I set the keyframes to start at a left of 0, then move 150px to the right at 50% of the animation and then 150 to the left at the end of the animation. I also set it to loop infinitely.

(slide23)

And here you can see how animation direction works. The top example is using alternate direction, so the animation goes from start to finish, finish to start.

The second example is exactly the same, except it has animation direction removed, and you can see the animation performs start to finish, then jumps backward to start and goes to finish again.

(slide24)

Combining transitions, transforms and animations can produce some really interesting results. Here, we’re changing several properties. We’ve set the div to start animating when hovered over, and to transition between several background colours and border radius amounts.

I really recommend just sitting down for an hour or two and making up your own animations just to see how everything works.

(slide25)

Now I’d like to show a few real examples of how we can use these properties on every day sites. The trick is to keep the animations subtle and in good taste. No flashing news tickers please.

(slide26)

Hired.im is a job board I launched with a friend of mine, Paul Maloney. We created this project because we wanted to help support the community, so we decided to donate half of all the listing fees to an organisation, Code Club, that teaches kids how to code.

We’ve also just launched a directory for those looking for work and are hoping to be able to give away more prizes and host some fun events in the future.

(slide27)

Paul was the one who designed the site and decided to make the logo look like a hanging sign. I don’t remember who’s idea it was originally to animate the logo, but I thought it would be a great idea to make it swing slightly, as if swaying in a gentle breeze. When the user hovered over it would swing with more gusto, as if you actually pushed it or a heavy wind came through.

I wanted to make sure the effect was very subtle so it wouldn’t distract the user, but thought that doing something slightly crazier on hover wouldn’t be too much of an issue. This entire animation was done using CSS3, with a tiny bit of JS to add and remove a class.

Let’s take a look at how I did this.

(slide28)

Preparing the image for animation took a bit of tinkering to figure out just how to get it to pivot correctly.

For a swinging animation, you need to make sure that the point the image needs to swing from is exactly in the middle of the image, otherwise the pivot will be off. You can easily accomplish this in Photoshop using line guides and canvas size.

In my example, you’ll see that there’s a circle, or knob, that the swing looks to be hanging off of, and that’s where I wanted the image to pivot, so that’s where I’ve created my centre.

(slide29)

Let’s start by looking at the code for the more subtle animation – when the user isn’t interacting with the logo at all.

You can see I’ve first positioned the logo, including giving it some major negative margins to compensate for that extra space in the image, needed to ensure it pivots correctly.

Our logo needs to swing to the right and left just slightly – so in it’s regular state, I added a transition to ensure movement and a transformation of 0 – because we wanted it to start where it is now (already slightly “swung”).

But how to make sure it swings backwards just a bit? I added a class of ‘right’ to the logo to give the transformation something to go back on it.

This is where the JS comes in – we’ll need to toggle the “right” class on and off in order to make the sign swing smoothly and without stopping – this is accomplished by a simple toggleClass and setTimeout in jQuery. Combining jQuery and CSS3 is a fantastic way to extend the functionality of your animation and gives you the benefits of both worlds!

(slide30)

For the major swing on hover, I simply increased the degree of rotate in my transform. This time, I also added a positive degree to the regular hover (without the right class) to insure it really went wild.

(slide31)

Alternatively, this could be coded with an infinite animation loop and keyframes, something like you see above. This would also negate the need to use any JS, but I thought this was was slightly cleaner. It’s really up to you.

Some people get a bit confused on whether they should use transitions or animations – but in all honestly, it really doesn’t matter. Sometimes it’s faster to use one over the other, but other times, it doesn’t make much of a difference. There shouldn’t be any difference performance wise either if you’re just creating something small.

This is an example of a small animation that literally took a couple of minutes to implement, but that makes a big difference to the site’s look and feel. Let’s move on to the next example to see what else we can do.

(slide32)

This site was a portfolio built completely in WordPress and has a ton of different animations and fun little features – it was really fun to code. I’m still getting my head around moving from JS to CSS3, and making sure even older IE browsers can deal, so not everything I do animation wise is in CSS3 – in fact, most is still in JS and jQuery. In this site, I’ve got menu items popping out one at a time on load, off screen sliding content areas, some faux parallax and sticky headers, AJAX and a slider plugin going on.

(slide33)

There was one part though, that I thought would work fantastically with CSS3 animations, and that was the side sliding content rollovers in the project quick view area. Basically, the client wanted the name and type of the project to slide in from the left over the thumbnail on rollover

This was accomplished easily, by just placing the content I wanted in the rollover inside a span. I then gave it a position absolute with a negative left that was the same size of the thumbnail to put it out of view. Then it was give a basic transition of “all” (although I could’ve specified “left” as well), a speed and some easing. On hover, it simply has a left of 0. It was that easy and such a lovely animation!

(slide34)

My third example is from a blog I did for the DC Internships program, which aims to get college students government internships. This was another site that was very dynamic and animations based – and again I chose to use CSS3 animations in a few places that weren’t necessary to the site’s overall structure.

In this case, we wanted to animated the red “Start Now” button on the very right hand of the screen – it need to come out to the left, move back in to the right some and then pop back out to the left again, with a sort of bouncy effect.

(slide35)

I created this using CSS3 animations. I set four milestones in the keyframes to take care of the left to right animation – the button would start with 15px hidden out of sight. Halfway through the animation, it would come to the left all of the way, then 80% of the animation it would move to the right 3px, and then at the end of the animation it would move all the way back to the left.

You may have noticed that my animation rule is much, much shorter than in previous examples. Thankfully, like other CSS rules, animation has a shorthand!

You’ll simply need to list the name of the keyframes, in this case I had named it “bounce”, the length you want the animation to last, the amount of times it needs to repeat and the easing effect in that order. It makes remembering and dealing with animations that much easier!

You might be wondering why I set a left of 0 on hover when the animation itself already takes care of moving it to the left. For browsers that don’t support this animation, it’ll simply  ignore the animation rules completely and move to the left once on hover. Which brings me to…

(slide36)

Browser compatibility!

In this talk, I’ve been using the proper syntax for CSS3, but unfortunately, no browser can actually read it! In reality, we must make sure we prepend our CSS with all of the lovely vendor prefixes that have to be used for the rest of CSS3.

Personally, I only prefix for webkit and mozilla browsers, but you’re welcome to include IE and Opera as well. Make sure you add the prefixed version before the correct, non-prefixed version.

If a browser can’t read either the prefixed or the correct syntax, it’ll simply ignore it. If you add rotate transforms to an image, it’ll simply present itself as straight. Most of the time, using animations doesn’t break the site at all in non-supporting browsers, just like the rest of CSS3, which is why using them is so darn awesome.

(slide37)

Using prefixes can suck sometimes, as it tends to muddy up your code, but it’s not terrible if you’re a neat coder anyways.

Here’s the last example, from DC Internships, shown in real life code. Not too pretty I know – and this one is just supporting Firefox and Webkit prefixes too.

(slide38)

Currently, Firefox, Safari, Chrome, Opera and most smartphone devices can use all CSS3 animation types, including transforms and transitions, as long as you use the prefixed versions.

However, Opera Mini and all versions of IE don’t work with animations, transitions or transforms at all. IE10 WILL support these however and is planned to be released *hopefully*  soon. You can never say for sure with Microsoft.

Don’t be fooled by IE though, just like border-radius and other CSS3 properties, animations, transitions and transforms can be used – as long as you’re not using them for something pertinent to the site’s functionality, unless you have some kind of fallback. All of the examples shown here are used in production sites today, without a fallback – and everything works. IE just ignores the CSS3 properties completely – which mean it defaults to a normal rollover.

(slide39)

None of the examples shown are earth shattering, but it’s the little things that count – and the little Easter eggs that really bring a smile to visitors’ faces as they navigate around your sites. Most clients can’t justify recreating their logos in CSS3 or animating a cartoon, but the smaller stuff is so quick, it can actually save them money as you don’t have to spend time hunting down or customising a jQuery plugin.

(slide40)

I’ve hoped you learn that you can include lots of nifty CSS3 animations and image manipulations without going crazy or having to spend hours on the effects.

(slide41)

You can find me online by going to www.amberweinberg.com, or on twitter @amberweinberg. My slides and notes are up now at X

I want to thank you guys for taking the time to sit through this – hope you enjoy the rest of Reasons! If you have any questions, please feel free to come up to me.