CSS Fundamentals: CSS 3 Transitions

CSS Fundamentals: CSS 3 Transitions

Tutorial Details
  • Language: CSS
  • Difficulty: Easy
  • Estimated Completion Time: 30 min
  • Premium Video: Available
This entry is part 10 of 16 in the CSS3 Mastery Session
« PreviousNext »

As CSS3 rolls out around the web, it is bringing some interesting new presentational techniques along with it. Today, we’ll review the basics of using CSS3 transitions and animations to add an extra layer of polish.


Step 1 – Link Transitions

To begin, we’ll work with some basic techniques – firstly a simple change of text color when a user hovers over a specified element.

a { color:#000; }
a:hover { color:#f00; }

Here, we change the text color to red on hover. Now, with a little CSS3, we can create a much smoother look by gradually fading the color.

a{
   color:#000;
   -webkit-transition:color 1s ease-in;
}
a:hover{color:#f00;}

We’ve added the css property, -webkit-transition. Note that the -webkit prefix specifies that this will only work in Webkit engines, or Safari and Chrome. Luckily, other modern browsers have their own implementations as well. A full statement covering all browsers might look similar to the following:

a {
   color:#000;
   -webkit-transition:color 1s ease-in;
   -moz-transition:color 1s ease-in;
   -o-transition:color 1s ease-in;
   transition:color 1s ease-in;
}

Please note that, for this tutorial, we’ll be focusing exclusively on the webkit implementation. After the declaration of the property, we have the values “color 1s ease-in.” This is the shorthand declaration; the three values represent:

  1. the property to be transitioned
  2. the duration of the transition
  3. the type of transition

In this case, we transition using ease-in, which will begin the transition slowly, and speed up into the transition.


Step 2 – Background Transitions

Another basic use of changing states is to change the background of an input box on focus.

input.ourInputBox:focus{
 -webkit-transition:background-color 0.5s linear;
 background:#CCC;
}

This time, we put the transition declaration into the hover state, so that we aren’t adding additional unnecessary classes to the CSS. We apply the transition once the input box acquires focus.


Step 3 – Transitioning Multiple Properties

CSS transitions are actually relatively straight forward to add to existing hover functionality, and give your
site that extra polish for browsers that support CSS3.

To take things a step further, we can also transition multiple CSS properties using the longhand versions of the CSS3 transition.

a.thebg {
 color:#000;
 background:#f00;
 padding:5px;
 -webkit-border-radius: 5px; 

 -webkit-transition-property:color, background;
 -webkit-transition-duration: 1s, 1s;
 -webkit-transition-timing-function: linear, ease-in;
} 

a.thebg:hover {
 color:#f00;
 background:#000;
}

This time, the background and text color changes on hover, so we can target both of these properties with our transition.
We simply split the transition: first we have -webkit-transition-property and separate the different values with a comma. So we target the color and background properties, respectively.

-webkit-transition-property:color, background;

Then we set the duration of the transition using:

-webkit-transition-duration:1s, 1s;

These are referenced in the same order as the first statement; this time, however, both values are set to 1s.

Lastly, we set the timing function, and set two different values: the first, linear, relates to our first declared variable – color; and the second relates to the variable background.

So, we’ve set the color to a linear change over one second, and the background to ease-in over that same time period.


Step 4 – Putting the Pieces Together

CSS3 transitions start to come into their own when they’re combined with other new CSS properties.

You can review examples of using overlapping elements and transitions on Andy Clarke’s For a Beautiful Web.

Let’s create a simple example of animating a pop out sign.

We first create the bounding box for the signpost, and give it a relative positioning context to ensure that we can
position items absolutely within it.

#signpost{
 width:60px;
 height:196px;
 position:relative;
}

Now we place the box on the page and put the pieces of our sign within it.

<div id="signpost">
	<img id="post" src="post.png">
	<img id="sign" src="sign.png">
</div>

Next, the post is positioned with a z-index of two, to place it on top of the sign.

#post{
 width:79px;
 height:196px;
 z-index:2;
 position:relative;
}

Now, we add in the sign, positioned underneath the post, and rotate it with the CSS3 transform property.

#sign{
 height:46px;
 width:80px;
 position:absolute;
 top:10;
 left:60;
 -webkit-transform-origin:0 0;
 -webkit-transform: rotate(86deg);
 z-index:1;
 -webkit-transition:-webkit-transform 0.5s ease-in-out;
}

The sign is rotated using -webkit-transform: rotate(86deg), and is positioned under the post. To ensure that the sign rotates around the proper point, we must change the transform origin to the top left corner: 0, 0.

We set the transition to change the -webkit-transform property over 0.5s with an ease-in-out profile, and on hover, we rotate the sign back to its original orientation.

#signpost:hover #sign{
	-webkit-transform:rotate(0deg);
}

We do this on the containing #signpost:hover rather than on the hover of the #sign itself.


Step 5 – Introducing Animations

We can now tie all of this together, using webkit animations, which give us the power to carry out things such as continuous rotation.

We begin by creating two circle images, and positioning them inside a containing div – as we did with the signpost above.

<div id="circles">
	<img src="outer.png" width="180" height="180" class="outercircle"/>
	<img src="middle.png" width="90" height="90" class="middlecircle"/>
</div>
#circles{
	width:180px;
	height:180px;
	position:relative;
}
.outercircle{
	width:180px;
	height:180px;
	position:absolute;
	z-index:1;
	top:0:
	left:0;
}
.middlecircle{
	width:90px;
	height:90px;
	position:absolute;
	z-index:3;
	top:45px;
	left:45px;
}

Now we need to define the animations; we’ll spin the circles in opposite directions, so we need to set up two animations.

@-webkit-keyframes spin {
from {
	-webkit-transform: rotate(0deg);
}
to {
	-webkit-transform: rotate(360deg);
	}
}

@-webkit-keyframes spinrev {
from {
	-webkit-transform: rotate(0deg);
	}
to {
	-webkit-transform: rotate(-360deg);
	}
}

The animation is given a name for reference, in this case “spin” and “spinrev.” Then, we assign them a to and from value; so we rotate the image from
0 deg to 360 deg using webkit transform, and to -360 for the reverse.

Now we assign this animation to the hover states. Note that, if we assigned it to the normal state, the animation would run immediately when the page is loaded.

#circles:hover .outercircle {
	-webkit-animation-name: spin;
	-webkit-animation-iteration-count: infinite;
	-webkit-animation-timing-function: linear;
	-webkit-animation-duration: 10s;
}	

#circles:hover .middlecircle{
	-webkit-animation-name: spinrev;
	-webkit-animation-iteration-count: infinite;
	-webkit-animation-timing-function: linear;
	-webkit-animation-duration: 5s;
}

We reference the animation name we created earlier (-webkit-animation-name: spin;). Then, we declare the number of times we want the animation to run (-webkit-animation-iteration-count: infinite;).
In this case, infinite will keep it going round and round whilst the #circles div is hovered upon.

We next set the timing function (-webkit-animation-timing-function: linear;), and, finally, we set a duration for each iteration – in this case, it will be ten seconds (-webkit-animation-duration: 10s;), and five for a complete revolution.


Step 6 – Graceful Degredation with Modenizr

Once we have everything working, we should consider our users who are browsing without CSS3 capable web browsers. This is easily accomplished using a JavaScript library such as Modernizr, which adds classes to the HTML element relating to the browser capabilities.

Using the sign post example above, browsers that don’t support CSS transforms will not place the sign under the post correctly; so we can target these browsers and simply hide the sign until it is hovered over.

.no-csstransforms #signpost #sign{
	display:none;
}
.no-csstransforms #signpost:hover #sign{
	display:block;
}

It’s as simple as linking to the Modernizr script, finding the appropriate class name, and then creating a separate CSS statement for that instance.


Conclusion

That’s all for now. I hope you enjoyed it! Let me know if you have any questions/comments below!

Add Comment

Discussion 75 Comments

Comment Page 1 of 21 2
  1. My Name says:

    Fundamentals*

  2. Mike Taylor says:

    Nice work. This is one of the better-written articles on this site in a long time. Perhaps that’s why there are so few comments.

  3. CULTOFDEATH says:

    I don’t understand the new CSS 3 features. Why complicated something that suppose to be simple and efficient. CSS was not created to separate the styling from the coding ? I just don’t get it!. Try to make some animation with css sound like a crappy solution to me. Maybe i am wrong!

    • Jeffrey Way says:
      Staff

      What would you recommend instead? JavaScript? If you can make it work in a browser, regardless of whether JS is enabled or not, why wouldn’t you?

      • Ulrik says:

        I think i know what you mean Cult. And no Jeffrey, maybe there should just be an alternative that is cross browser supported like stylesheets, just for the animation/coding bits, since css is for the looks. ASS – Animation Style Sheet? :)

      • Matthew Hunt says:

        Agreed, and if it just works, you dont need to call a script or add more code than you would need to using css animations.

      • Leonardo says:

        I think CSS should be used for styling and JS for animations.
        True, JS can be disabled. But so can CSS!

        And if you switch of JS you might as well go back to ye olde black & white TV (without remote control)

      • Leonardo says:

        I think CSS is for styling and JS for (among other things) animations.

        Yes, JS might be disabled, but this goes for CSS as well plus users can override CSS with their own browser stylesheets.
        Even images can be disabled.

        But: I read that over 60% of internet users use IE, which to me means that over 60% haven’t a clue about things like HTML, CSS, JS etc (otherwise they wouldn’t use IE…).
        So how many are capable of disabeling JS in the first place?

        Then I wonder how clever these transitions are if you need to specify -webkit, -moz, -o and no-prefix.

        And how about older versions of firefox etc?

        Furthermore, these effects are kindergarden stuff compared to what you can do with JS (and/or the many libraries)
        So chances are, that you will need JS next to these transistions.

        Having said this, everybody should use the tools with which they are most comfortable, but these transitions wouldn’t be my choice.

      • Alex Hall says:

        I would like to point out that animation is technically a stylistic feature of a website. It’s an interactive style, much like a hover effect. Your just adding a transition to the style change, which should be part of CSS leaving us to not have to worry about huge lumps of javascript code to create the same effect.

        Nice walkthrough of the various features of CSS3. I have noticed, quite annoyingly, that you can’t animate a background gradient, only solid colors, which would’ve been nice.

        The other point to note, I guess, is that until there is proper all-round support for this (which will take YEARS) it can only be used as a progressive enhancement to a page, and for things such as transitions that will only be available for webkit users (until FF 3.7 finally gets released).

        It’s personal preference, in much the same way as creating transitions in javascript. If you want a bit of ‘funk’ add them, if you’re going for simplicity, don’t.

    • Matthew Hunt says:

      I’m not sure who said css was supposed to be simple. In fact most people complain about what you can’t do with css, especially when it comes to typography options.. The deal with the animations I suspect is something that webkit ( Apple ) is pushing for.. take a look here: http://www.w3.org/TR/2009/WD-css3-animations-20090320/ all of the editors of this page are from Apple. Once specifications are implemented by browsers, you won’t need their -webkit- prefix.

    • Dave Sparks says:
      Author

      The only obvious and widely used alternative is JavaScript and most people use things like jquery and mootools which make use of CSS selectors anyway so why not just write it into your CSS?
      You don’t need to include it all within the main body of your CSS coding, maybe create a new css file animations.css then you can keep your animation coding separate.

      The main downside at the moment is the lack of cross browser support so it is kind of limited to an enhancement feature, but at the same time people still have to make considerations for browsers with JavaScript enabled so you still have the same problems.

    • Mars says:

      why wouldn’t u use flash for just your little animation parts?

      • Alex Hall says:

        Ermm… because it’s flash?

        Why should you (or would you want to) have to create a swf that is tricky to make a small change to (i.e. re-opening the fla, make the changes, republishing and uploading again), has plenty of obsolete code (bloating the page) and gets blocked by ad-blocking programs?

        You could simply put in a line or two of CSS into a stylesheet to do the same thing, which is easier to manage and can be re-used without adding extra bloat to a page.

    • Lavino Lavazzi says:

      All the animation could and should be made with SVG… if the browsers would the support it!

      Further info http://www.w3.org/TR/SVG11/animate.html

    • Can’t get easier than this, however how come ‘transition’ is still not accepted by Chrome.. we still need to add -webkit-.

  4. enatom says:

    thanks for this tutorial

  5. lololololo says:

    THIRD

  6. David Moreen says:

    Honestly I am in love with CSS transitions, the only downside is that not all browsers support it…

  7. Lori bien says:

    your animation ain’t works in my browser(ie8.0 & lastest version of firefox)

    • Jeffrey Way says:
      Staff

      Yep. That’s right. Did you see the “Use Safari or Chrome” heading? :)

      • Stefan says:

        The more the reason that we are not ready for this stuff, when its compatible with at least two thirds of the leading browsers we should start taking it a bit more seriously, and certainly the markup would have improved by then.

        Well for now I’m sticking to JS and … Flash. There I said it! I think Flash is an amazing addition to the web developer’s arsenal!

    • Doug says:

      Firefox is only supported with version 4, which is still in beta. If we are lucky we might get css3 selectors in IE9.

  8. Bono says:

    I need to study CSS3 more.. Thanks for sharing! cheers!

  9. obviously using css transitions is less complex than including jquery and doing it with that way. Assuming a world in which all browsers support css3 what then should still be animated with js?

  10. Wow

    That’s great !

    Thanks !

  11. Matt says:

    I love this concept and I’ve been wondering how long it would take to finally implement in a browser (about 3 years ago…), and I am a little iffy on implementing any CSS3 on my sites until FF, Chrom, IE and all the other browsers support it.

    But hey, practice can’t hurt right?

  12. Stephen Webb says:

    Being interested in the development of CSS3 I immediately wanted to find out more about the development of the Webkit engine, and seeing these examples wasn’t disappointing. It really appears that CSS3 is going to revolutionise web development the same way that moving from Tables to DIVs did. There is so much potential and application for the new technologies, however there is still of course one downside.

    All these developments are fantastic, but the fact that none of them are currently supported by Internet Explorer makes them very limited in usage at present. With no word on whether future versions will support the technology, or when it we are likely to see it addressed, the new CSS3 developments will have very limited functionality.

    I’d like to see other designers views on this matter. Obviously some of the effects can still be achieved by Javascript workarounds, but this patching up method of working will still hold back the CSS3 implementation until it is universally accepted across all browsers.

    • Ahmad Alfy says:

      I *think* when these are adopted by the W3C, it’s gonna be supported by all the browser. Right now we should be discovering its potential and play around with them… Maybe not use it for our websites! but to blog about it, share experience… etc

      Some guy spammed a link in a reply for the first comment showing how to use CSS3 to create and accordion like effect! All of us use JS to create that! You know what that mean :D ? ITS THE FUTURE!!!

      Hope by this time we don’t have to worry about IE6!@!!!

  13. Ahmad Alfy says:

    Look at JavaScript today; most people use jQuery or MooTools to create these (WOW) effects without programming skills… Find some tutorial here and there, copy and paste then you’re done.

    I think CSS3 is going to replace *this part* in JavaScript.. The presentational part. Even if we don’t really understand them now, It will be clear soon. Why include a JS file and add some code when it can be done by 2 – 3 lines with CSS? What concerns me more, I can understand it! People without programming skills can do it!

    It’s the future IMHO (cause I really suck with Javascript :D)

  14. Helen says:

    Did you check if the -moz-… and -o-… really works? I did! :)

    • Bryan Watson says:

      For everyone’s information, it doesn’t work in Firefox 3.6, but apparently Opera 10.5 pre-alpha has support for CSS3 Transitions.

    • Dave Sparks says:
      Author

      They won’t work at the moment, however it is useful to have them there for when these browsers start to offer support.
      It should then give you very little, possibly to change if you want to implement these effects.

  15. very nice and useful indeed! :)

  16. Hassan says:

    The animations are pretty cool.

  17. thom22 says:

    Nice article, hope its not years and years before all browsers support this.

    Can anyone point me in the right direction for a nice rotate method using jQuery to get a similar effect to the one used here with webkit? greatly appreciated

  18. I like CSS animations very much, this is great!

  19. I wish browsers would adopt changes sooner xD

  20. 2&B says:

    The circles demo does not work for me (OSX Safari 321).

    Agree on previous post about creating animations with SVG: that should be the solution.

    2&B

  21. Bennie says:

    I think i know what you mean Cult. And no Jeffrey, maybe there should just be an alternative that is cross browser supported like style sheets.

    Auto Accidents Lawyer Temecula

  22. AndC says:

    Interesting use of CSS. Useful to know and use in the right context. I agree that more complex animations should be created using JS, but for something simple, this is an elegant solution.

  23. Very great work. thx for it. You helped me out.

  24. SpeedofMac says:

    This is a nice introduction to CSS3 transitions. It might be good to add the -moz prefixes to your demos soon. Firefox 3.7 (there is an alpha version called Minefield, currently at version 3.7a5pre) supports CSS3 transitions, and this would be a good spot for Minefield users to flex their newfound CSS3 transitions muscle.

  25. M Plant says:

    Great, but how long before all browsers catch up?

  26. aamedya says:

    The blog is very informative.

  27. Jeff says:

    it’d be nice if we could transition background-images too. Maybe we’d be able to fade from one background to another.

  28. micksatana says:

    thx a lot :)
    very nice examples and easy to follow..

    ps. In the signpost example, ‘left’ and ‘top’ in css should put ‘px’ after the value so the position of the sign will be correct in Chrome.

  29. martin says:

    it’s not cross-browser compatible, so it sucks.

  30. flxa says:

    I can’t believe the amount of people that have commented here that bag out the fact that it’s not cross browser compatible or suggest things like using Flash (seriously) as an alternative or suggest that animation should be restricted to Javascript or suggest that a user may turn off Javascript so what if they turn off CSS, especially that last one I mean come on, if they turn off CSS are they really expecting to see a well crafted website? Will they care if the animation doesn’t work?
    It’s just a tutorial explaining how to use an experimental method that has been created. There is nothing forcing people to use it.
    So thanks for the great tutorial, keep up the good work!
    It’s a shame IE9 didn’t fit this one in but it’s still in Beta so we’ll see what happens next.

  31. rickzwebz says:

    CSS3 looks very exciting, but how long will we have to wait until it works in all browsers? If we are lucky it might work in Explorer by 2020.

  32. Great, but how long before all browsers catch up?

  33. JGarrido says:

    Does anyone know if there is a way to always have the animation playing?

  34. Don’t get me wrong, I dig animation when it comes to creating another video or a great flash-based game… hell, I even coded tons of director lingo stuff “back in the days”.

    But when it comes to animation in css3, I’m starting to see zombies at the horizon, worshiping an animated GIF that generates more eyeburn than IE can. ;)

    But hey, back to that late-80′s feeling where thousands of badly designed websites pop up, being animated in the most useless places, or – even worse – all over.

    I can imagine a logo being “animated” to give it that extra twinkle, but even paralax movements scripted in javascript tend to drain both CPU power and user attention. So why put animation into stylesheets? We could’ve scripted the canvas instead, making that our battleground for moving pixels.

    Oh well, I guess I’m growing old… asking myself if “animation” really fits into a “stylesheet” in the first place. I’m asking myself if a “standard” should be enlarged with this or if this wouldn’t be a good starting point for an additional standard. (Dreaming of an “animate” tag for the head where you can point to your animation scripting file… keeping content and style seperated… and also keeping the animation in a seperate box. Somewhat like a racing car has a nice painting and a good speed. But both hardly have anything to do with each other.

    PS: I hope that in 10 years when HTML5 is finalized, a “stylesheet” still is a “style”-”sheet”. But that’s probably just me… thinking in boxes, working with folders and coding sites static where “dynamic” does not make sense. ;)

  35. Jason says:

    Dave, there’s an unclosed strong tag in the Tut details thats making the whole page bold.

  36. slow says:

    .no-csstransforms #signpost #sign{
    display:none;
    }

    that’s bad css. use only a selector or a class.

  37. sawebdesigns says:

    Im learning some cool new stuffs

  38. Bold says:

    Why is everything in bold?

    The or tag is no t closed somewhere?

  39. Nice post. I liked to know about Modernizr. Thank you.

  40. Sathish says:

    Really Awesome!

  41. Really great collection, thanks for sharing! I certainly hadn’t considered using easing on links with CSS3 I am still using J-Query for that effect…

  42. Ladida Cafe says:

    woww nice, thanks for the tricks, maybe I can add -moz- here so it can read by firefox too :)

  43. Well written article, thanks (well apart from the typo!)

    I have to agree with Mike a bit that im not sure that CSS animation is a good think, remember when people first discovered animated gifs ?!?

  44. Sam says:

    Thanks for sharing the basic CSS3 transition effects..Nice tutorial.

  45. Dimitry says:

    Hello to All,

    Seems this example http://nettuts.s3.amazonaws.com/581_cssTransitions/demos.html doesn’t work in CHROME at all.

  46. sylhet says:

    The link you given not working (Andy Clarke’s For a Beautiful Web.) http://forabeautifulweb.com/buy/dvds

  47. Tasha says:

    love it!!

Comment Page 1 of 21 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.