CSS3 Transitions to replace JavaScript animations
Until recently whenever I had to do the simplest animation I always had to use JavaScript code.
If you're using jQuery it's pretty easy to make simple effects.
The most known ones would probably be slideDown() and slideUp().
Custom animation is also pretty easy with jQuery:
1
2
3
4
5
6
7
8
9
10
11
12
$('div.red').hover(function() {
$('div.red').animate({
width: '+=50',
height: '+=50'
}, 200)
},
function() {
$('div.red').animate({
width: '-=50',
height: '-=50'
}, 200)
});
(Working example)
This step seems to be getting more and more unnecessary, especially with mobile websites, thanks to CSS 3 transitions and their support by the major browsers.
Transitions are basically a way to specify how long will it take for the property to change properties, which is very similar to the way JavaScript animations are done.
So basically, if I have a DIV element , and I would like it to increase its size (width and height) on hover, I would write something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
div.red {
position:absolute;
background-color:darkgray;
padding:5px;
cursor:pointer;
width:140px;
height:20px;
transition: width 1s, height 1s;
}
div.red:hover {
width:280px;
height:40px;
}
(Working example)
The crucial piece here is the "transition" part, which defines the time it takes until the transition is made to change from one value to the other.
A very useful trick here would be to just use all (e.g. "all 1s"),
to define all property transitions on one go.
This could potentially spare you a lot of time coding, especially since almost all animations on a website are pretty basic (we're not making a movie over here).
There are some more sophisticated animations.
For example, if you're interested in animating 3d shapes, though I can't say that I've found much usage for it (most likely just eye candy), this is also possible, and renders (at least on chrome) better than JavaScript animations too !
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
div.red {
position:absolute;
background-color:darkgray;
padding:5px;
cursor:pointer;
width:140px;
height:20px;
transition: all 2s;
}
div.red:hover {
transform: rotateY(180deg);
-webkit-transform: rotateY(180deg); /* Safari and Chrome */
width:280px;
margin-top:20px;
height:40px;
}
(Working example)
rotateX, rotateY and rotateZ are available, there's also rotate3d(x,y,z,angle)
(e.g. rotate3d(1,1,1,180deg) to make all of the axes move 180 degrees).
It seems that the new CSS 3 tools are catching up with some graphical gaps that were traditionally solved with JavaScript (and thus had a lot of different implementations), could be a little tricky to learn in the beginning but in they're definitely more elegant and increasingly become the standard.