Skip to content

Instantly share code, notes, and snippets.

@wazery
Created January 10, 2014 05:50
Show Gist options
  • Save wazery/8347550 to your computer and use it in GitHub Desktop.
Save wazery/8347550 to your computer and use it in GitHub Desktop.
CSS3 Transitions and Animations
Introduction to CSS3 Animations
=====================
**CSS3 came with a lot of handy features that changed the website styling dramaticaly, one of those is animations. There is a [specification][1] for the animation module since a couple of years now. Before CSS3, animating any element in your web page wasn't an easy task. Some of the techniques you might used in the past are Flash animations, animated GIFs, or using some JavaScript library that have animation techniques like JQuery.**
In this tutorial I will introduce you to how to use transitions, transforms, and animations by creating some simple examples.
----------
CSS3 Transitions
============
Transition is simply a feature that allows you to add some effect when an element changes from a state to another.
##How we can use Transitions?
If we have a link with color of white that have the following simple style:
a {
color: white;
}
As you know this link have some states like hover, focus, and active. What if you want the link to change its color to orange when the mouse hovers a long it? Then the transitions come in use.
a {
color: white;
-webkit-transition: color 1s ease-in;
}
a:hover {
color: orange;
}
Now we defined that the anchor tag will produce a transition of `ease-in ` which will make the transition begin slowly then speeds up (I will going to talk about some other types in details later on). this will happen every time the color property changes its value in any state of the anchor tag, and the duration of this transition will be 1 second.
An important thing to note is that `--webkit` prefix means that this transition will only work on any browser that supports the webkit engine. This is called a **vendor prefix** which is a way the browsers makers use to add support for newly implemented CSS features, they use it to indicate that this property is still under testing and working only for their browser. I will continue with the webkit version all over this tutorial, so you can change it while trying the exampels depending on your browser.
**Here are some of these prefixes:**
> - **Chrome**: -webkit-
> - **Firefox**: -moz-
> - **Internet Explorer**: -ms-
> - **iOS**: -webkit-
> - **Opera**: -o-
> - **Safari**: -webkit-
> - **Android**: -webkit-
The common practice is to first write the following prefixes and following them with the standard property, so our anchor tag style would be:
a {
color: white;
-webkit-transition: color 1s ease-in;
-moz-transition: color 1s ease-in;
-ms-transition: color 1s ease-in;
-o-transition: color 1s ease-in;
transition: color 1s ease-in;
}
a:hover {
color: orange;
}
> **NOTE:** In the above code we used the shorthand technique of declaring properties. the line`-webkit-transition: color 1s ease-in;` is a shot declartion for:
-webkit-transition-property:color;
-webkit-transition-duration: 1s, 1s;
-webkit-transition-timing-function: linear, ease-in;
###Multiple Transitions
What if we want to make transitions for multiple properties at the same time?
Lets assume we want to make a transition for the background property a long with the color property. We can do this simply by adding the background property: `
a {
color: white;
-webkit-transition: color, background 1s ease-in;
}
a:hover {
color: orange;
background: #000;
}`
####Here are the types of transitions
Property | Description
--------- | -----
linear | Transition effect with the same speed from start to end
ease | Transition effect with a slow start, then fast, then end slowly
ease-in | Transition effect with a slow start
ease-out | Transition effect with a slow end
ease-in-out | Transition effect with a slow start and end
cubic-bezier(n,n,n,n) | Your own values in the cubic-bezier function
####Using transforms with transitions
CSS3 has another handy feature called transforms which enables us to manipulate any element's spatial properties like rotation, scaling, translation, or skewing. Sure we can manipulate each property in any axes we want (x, y, z).
**So what about using the transforms and transitions in creating a loading spinner?**
Actually if we tried the below code we will have a spinner icon that only animate if a hover state is triggered. This isn't what we want to accomplish. We want the spinner to keep spinning no matter what the is the state of it. So the transitions isn't our perfect property, and here it comes importance of the **Animation** property.
Here is the simple code of a static spinner:
####HTML
<img src="spinner.png" alt="loading..">
####CSS
img {
-webkit-transition: -webkit-transform 0.5 ease-in-out;
}
img:hover {
-webkit-transform: rotate(90deg);
}
----------
CSS3 Animations
============
As we saw in the above example the transitions didn't help us accomplish the continuous motion, because transitions animate only if the state changed. Transitions don't provide complex motion capabilities.
Animations can alter page elements over time, we can specify when the animation start and when it end.
In animations we can also change multiple properties in any time we need. We can do that by specifying their values at different percentages of the animation duration. This can be accomplished by the`@keyframe` selector, but if we used it correctly. This property have a lot of values that we can alter depending on how we want it to work. So lets first try to use it in a simple example which is our spinner for sure.
img {
-webkit-animation: Rotate 1s linear infinite;
}
@-webkit-keyframes Rotate {
from { -webkit-transform:rotate(0deg); }
to { -webkit-transform:rotate(360deg); }
}
Also the animation property is still under development and so it has some vendor prefixes as it appears from the example above.
Now if you tried the snippet above you will found it working the perfectly the way we want it. Again I used the shorthand syntax to accomplish this. Which is as follows:
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
So we first give the animation a name, in this example I gave it the name 'Rotate' then the duration is one second, the timing-function is linear and we need to say that animation's timing function values are similar to those of the transition, which we described earlier. Here we gave the timing function the value of linear as wee need the speed to be the same from the start till the end. Lastly the animation will be working with no end, so we given the duration property the infinite value.
##Advanced Animations
Now we are going to implement a simple side scrolling game, as you see in the demo, there are some animating objects in which there animations are not just a linear animation like the space ship. We are going to see how to implement this.
All of the game assets are available under creative commons attribution license, I am not the original designer of them, I found them on the *Vicki Wenderlich's* [blog][2]
![Simple side scrolling game][3]
Here is the simple HTML code of it:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<img src="images/bg_front_spacedust.png" class="space_dust">
<img src="images/bg_galaxy.png" class="bg_galaxy">
<div class="spaceship"> </div>
<img src="images/laserbeam.png" class="laserbeam">
<img src="images/enemy_spaceship.png" class="enemy_spaceship">
<img src="images/asteroid_sm.png" class="asteroid_sm">
<img src="images/asteroid_lg.png" class="asteroid_lg">
</div>
</body
As you can see the objects are simply some PNG images. I gave each image a class so we can alter its style in our CSS. Now lets start what exploring what is more important, the CSS3 stylesheet.
I will not explain much about positioning elements like the background because we have some other important stuff to discuss here, so here is the CSS for our static elements:
body {
background-color: black;
}
.container {
position: fixed;;
top: 0;
left: 0;
background-color: black;
height: 480px;
}
.space_dust {
width: 100%;
}
.bg_galaxy {
position: absolute;
top: 150px;
left: 500px;
width: 20%;
}
Now lets see how we can animate our spaceship object.
.spaceship {
position: absolute;
top: 30px;
left: 100%;
z-index: 50;
-webkit-animation: spaceship_anim 10s linear infinite;
}
As you can see I gave the spaceship an initial position values and a high `z-index` to make sure that it didn't get hidden by any another object in the scene. I made an animation with the name `spaceship` and 10 seconds duration with a linear timing function, so it is clear that the speed will be the same during the animation.
###Animation Keyframes
Now we need to specify precisely the position of the spaceship object during each split of the animation duration, so here it comes the keyframes selector. The standard syntax for it is `@keyframes name_of_the_animation` but as mentioned earlier I am using the webkit version here, so it is clear for you that you can append each of the vendor prefixes. In the above example we used it with the "from" and "to" keywords respectively, but in this example we need a more precise definition for timings. As you can see in first line we indicated the position properties of the spaceship in the `0%` of the total duration of the animation, next we changed the values to make the spaceship looking like it is going down and advancing it in the screen to the right, and we kept doing that till the end of the animations, so now we have a precise keyframes of our animation with a simple and elegant code.
@-webkit-keyframes spaceship_anim {
0% { top: 30px; left: -2%; }
10% { top: 50px; left: 10%; }
20% { top: 30px; left: 20%; }
30% { top: 50px; left: 30%; }
40% { top: 30px; left: 40%; }
50% { top: 50px; left: 50%; }
60% { top: 30px; left: 60%; }
70% { top: 50px; left: 70%; }
80% { top: 30px; left: 80%; }
90% { top: 50px; left: 90%; }
100% { top: 30px; left: 100%; }
}
Now we need to add the enemy space ship animation which is no different that than the above, we will only reverse the keyframes position values!
.enemy_spaceship {
position: absolute;
top: 60px;
right: 100%;
-webkit-animation: enemy_anim 10s linear infinite;
}
@-webkit-keyframes enemy_anim {
0% { top: 120px; left: 100%; }
10% { top: 140px; left: 90%; }
20% { top: 120px; left: 80%; }
30% { top: 140px; left: 70%; }
40% { top: 120px; left: 60%; }
50% { top: 140px; left: 50%; }
60% { top: 120px; left: 40%; }
70% { top: 140px; left: 30%; }
80% { top: 120px; left: 20%; }
90% { top: 140px; left: 10%; }
100% { top: 120px; left: -2%; }
}
####Laserbeam
.laserbeam {
position: absolute;
top: 99px;
left: 10%;
opacity: 0;
z-index: 49;
-webkit-animation: laserbeam_anim 5s 1 linear 50ms;
}
@-webkit-keyframes laserbeam_anim {
0% { left: -230; }
100% { left: 75%; opacity: 1}
}
We need our laserbeam to be delayed for some small time before being shot, so we will use the delay property for that. As you can see the delay property is assigned with the value 50 millisecond. We set its opacitiy to 0 and in the `100% keyframe we set it back to one, this will give the leaser beam a nice fading in animation.
####Planets
Planets will animate also with this simple animation:
.asteroid_sm {
position: absolute;
top: 100px;
right: 0px;
-webkit-animation: sm_scroll 10s linear infinite;
}
.asteroid_lg {
position: absolute;
top: 250px;
left: 100px;
width: 15%;
-webkit-animation: lg_scroll 10s linear infinite;
}
@-webkit-keyframes sm_scroll {
from { right: 0px;}
to { right: 2000px;}
}
@-webkit-keyframes lg_scroll {
from { left: 100px;}
to { left: 1000px;}
}
Simply as it appears from the keyframes the small planet will animate from right to left and the large one in reverse.
###Multiple Animations
####Spaceship Gas Animation
What about creating an animation for the gas emitting from the spaceship? We declared the spaceship as a `div` so we can change its background image in the CSS code. Now we need to add another animation for that. We can do that in one line along with the position animation. In the code below we simply added the other animation after the comma.
-webkit-animation: spaceship_anim 10s linear infinite, spaceship_gas_anim 800ms ease-in-out infinite;
No we need 2 simple keyframes for the 2 images we have, so we can change the background-image property like so:
@-webkit-keyframes spaceship_gas_anim {
from {background-image: url("images/Spaceship.png");}
to {background-image: url("images/Spaceship2.png");}
}
----------
What you have learned so far
============================
After reading this tutorial you now have a clear distinction between CSS3 transitions and animations, and you know how to use each of them well. We explored also what is CSS3 transforms. I hope this tutorial was useful and interesting for you.
> **NOTE:** The resources for the tutorial are available in this [dropbox][4]
> link.
----------
[1]: http://www.w3.org/TR/css3-animations/
[2]: http://www.vickiwenderlich.com/2011/05/game-pack-space-flier/
[3]: https://dl.dropboxusercontent.com/u/71605080/result.png
[4]: https://dl.dropboxusercontent.com/u/71605080/sidescrolling.zip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment