Animation with CSS3 Transitions
CSS transitions let elements animate smoothly between states without JavaScript — swapping jQuery's fadeIn/fadeOut for a .fade class and opacity transition takes maybe 10 lines of CSS.
When interacting with elements on a webpage, we can use CSS to define the look and feel of different states. However, only two states are defined, so the interaction can seem choppy. CSS transitions allow elements to animate smoothly between states, which were previously made possible only with JavaScript.
Syntax, Prefixes
The syntax for a CSS transition is:transition: property duration
The only browser that doesn't support CSS3 transitions is Internet Explorer. All other browsers support it — with prefixes.
transition: width 2s;
-moz-transition: width 2s; /* Firefox 4 */
-webkit-transition: width 2s; /* Safari and Chrome */
-o-transition: width 2s; /* Opera */Fading In and Out
I've typically used jQuery,fadeIn() and fadeOut() to perform fading animations.
With CSS, we can define a fade class, used in conjunction with an in class.
.fade {
opacity: 0;
transition: opacity 2s;
-moz-transition: opacity 2s;
-webkit-transition: opacity 2s;
-o-transition: opacity 2s;
}
.fade.in {
opacity: 1.0;
}There are two states the element can be in, visibile and invisible, which we represent here with .fade and .fade.in selectors. When moving between the states, the element undergoes a transition in the opacity level, ranging from 0 to 1, which controls the transparency of the element.
When we want to hide or show elements, we assign it a class of fade. When the element needs to fade in, we add the in class; fade out by removing the in class.