CSS Fundamentals: CSS 3 Transitions

CSS Fundamentals: CSS 3 Transitions

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!

Tags: CSScss3
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • My Name

    Fundamentals*

    • TopDog

      Lo…yeah. This is an extremely bad typo.

    • designfreek

      Yup dude fundamentals!! Even I found one more article on these css effects http://ib.im/dxfzK ..

  • http://miketaylr.com Mike Taylor

    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.

  • CULTOFDEATH

    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!

    • http://www.jeffrey-way.com Jeffrey Way

      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

        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? :)

      • http://mhuntdesign.com Matthew Hunt

        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

        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

        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.

      • http://www.devseo.co.uk Alex Hall

        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.

    • http://mhuntdesign.com Matthew Hunt

      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.

    • http://www.kamikazemusic.com Dave Sparks
      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.

    • http://www.dystopiangrafix.tv Mars

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

      • http://www.devseo.co.uk Alex Hall

        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.

      • http://www.keironlowe.co.uk Keiron Lowe

        …Seriously?

    • Lavino Lavazzi

      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

    • http://www.lotusmarketing.ca Marketing Sherbrooke

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

  • http://www.enatom.com enatom

    thanks for this tutorial

  • lololololo

    THIRD

  • http://bloggerzbible.blogspot.com/ Bloggerzbible

    Nice. thanks

  • http://spotdex.com/ David Moreen

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

  • Lori bien

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

    • http://www.jeffrey-way.com Jeffrey Way

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

      • http://www.stefanvella.com Stefan

        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!

    • http://www.design-shift.com Doug

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

  • http://www.ninjacrunch.com Bono

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

  • http://taylorhutchison.com Taylor Hutchison

    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?

  • http://sonergonul.com Soner Gönül

    Wow

    That’s great !

    Thanks !

  • Matt

    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?

  • http://www.crearedesign.co.uk Stephen Webb

    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.

    • http://www.alfystudio.com Ahmad Alfy

      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!@!!!

  • http://www.alfystudio.com Ahmad Alfy

    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)

  • Helen

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

    • http://www.BryanWatson.ca Bryan Watson

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

    • http://www.kamikazemusic.com Dave Sparks
      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.

      • http://www.kamikazemusic.com Dave Sparks
        Author

        oops lazy typing

        It should then give you very little, possibly nothing to change if you want to implement these effects.

  • http://www.liberatocreative.com Maurizio Liberato

    very nice and useful indeed! :)

  • http://www.hassanc.co.uk/ Hassan

    The animations are pretty cool.

  • thom22

    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

  • http://www.go-shape.com Daniel Bidmon

    I like CSS animations very much, this is great!

  • http://michaelrijsdijk.nl/ Michael Rijsdijk

    I wish browsers would adopt changes sooner xD

  • 2&B

    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

  • http://duiattorneyriversideca.com Bennie

    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

  • http://duiattorneyriversideca.com Bennie

    I think it’s pretty cool post

    Auto Accidents Lawyer Temecula

  • http://www.andcwebdesign.com AndC

    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.

  • http://www.schrumpfschlaeuche.org Schrumpfschlauch

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

  • http://speedofmac.com SpeedofMac

    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.

  • http://www.trenethick.co.uk M Plant

    Great, but how long before all browsers catch up?

  • http://www.aamedya.com aamedya

    The blog is very informative.

  • http://iamjeffmarshall.ca Jeff

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

  • http://www.linkedin.com/in/micksatana micksatana

    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.

  • http://www.dreammediadesign.co.uk Dream Media Design

    great blog thanx

  • martin

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

  • flxa

    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.

  • http://www.winnipegreflections.com rickzwebz

    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.

  • http://www.vibegraphics.co.uk vibe web design

    Great, but how long before all browsers catch up?

  • JGarrido

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

  • http://www.e-sushi.net/ Mike Edward Moras (e-sushi™)

    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. ;)

  • http://jvdesigns.com.au Jason

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

  • slow

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

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

  • http://www.sonnydesign.com sawebdesigns

    Im learning some cool new stuffs

  • Bold

    Why is everything in bold?

    The or tag is no t closed somewhere?

  • http://codeNtronix.com Leonel Machava

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

  • Sathish

    Really Awesome!

  • http://www.sozodesign.co.uk Mark Plunkett

    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…

  • http://whatuget.blogspot.com Ladida Cafe

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

  • http://www.bluemonkeyweb.co.uk Andy – Coventry Web Design

    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 ?!?

  • http://codeinsects.com Sam

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

  • http://nettuts.s3.amazonaws.com/581_cssTransitions/demos.html Dimitry

    Hello to All,

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

    • http://www.just4designjobs.co.uk Sam

      Hi Dimitry, Its working fine in my Chrome, are you using the latest version?

  • http://www.esylhet.com/ sylhet

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

  • Tasha

    love it!!