Introduction to CSS Transitions

Share this video with your friends

Send Tweet
Published 8 years ago
Updated 5 years ago

Learn how to use native CSS transitions to automagically add motion to your application. By specifying a simple transition rule, changes to the values of specific properties can be interpolated over time to give a graceful, polished look and feel to what used to be a jarring and sudden transition.

[00:02] Sometimes you find yourself in a situation where you have all of your logic in place and all the behavior looks the way it's supposed to look, but you'd like to add a little bit of polish. Here, we've got a sample application we've built where, when you click the little cards, their opacity goes down to zero, and you can see the image behind it.

[00:22] We show this to our client, the World Wombat Federation, and they say, "Oh my God, that's exactly what we want. That looks so great. Except, gosh, is there any way to make that look a little bit more polished? That's just so jarring. It goes from this beautiful yellow box to this beautiful wombat, but it's so sudden. Can we transition that somehow?"

[00:46] You might think to yourself, "Oh crap, I didn't budget transitions into this. I have to go back and research how to make my jQuery click handler now transition stuff, put in timers, and how to..." All of this, because we've all been there before, right? We all know how the little stuff like this tends to be the thing that gets you. You spend 20 percent of your time architecting this beautiful, complex application, and then 80 percent of your time just trying to make the fricking animations line up right or get the style pixel perfect.

[01:18] Look, here's great news. With CSS Transitions, all of this can just be automated for you in the CSS without having to change any of your additional code. The way it works is like this. As you can see, when you click right now, all that's happening is that the open class is being toggled on that cover object here. When the cover has the open class attached to it, the opacity goes to zero. When the cover does not have the open class attached, opacity is not specified, and so it defaults to one.

[01:53] When we click this, all that's really happening, right, is that we're changing the opacity value. CSS Transitions allow us to say this. Anytime the opacity property changes, transition that, animate that, interpolate those opacity values over whatever duration I give you. Now, when I click, instead of immediately setting opacity to zero, it's going to enter this animation loop where opacity is going to approach zero over 500 milliseconds. Now, we've got a much nicer little animation there.