Animations & Keyframes
While you can use JavaScript to create animations on the web, you can also use just CSS. Using CSS offers some benefits:
- These do not require any JavaScript
- They require fewer resources like memory, making them execute more quickly and appear smoother
- The browser has control over these on tabs that are open but not currently being viewed.
The animation Property
The animation property in CSS allows you to set the following (and more) in a shorthand:
animation-delayanimation-directionanimation-durationanimation-iteration-countanimation-name
animation: @keyframes | duration | easing-function | delay | iteration-count | direction | name;
animation: 3s ease-in 1s 2 reverse slide-in;
The @keyframes Rule
The @keyframes CSS at-rule controls the intermediate steps in a CSS animation sequence by defining styles for keyframes (or waypoints) along the animation sequence. This gives more control over the intermediate steps of the animation sequence than transitions.
@keyframes slide-in {
from {
transform: translateX(0%);
}
to {
transform: translateX(100%);
}
}
Timing, Iteration Count, & Direction
Adjustments to the timing, count, and direction of your animations can also be made.
Timing Functions
Syntax Example
/* Animation Shorthand: */
animation: @keyframes | duration | easing-function | delay | iteration-count | direction | name;
/* Options: ease, ease-in, ease-in-out, linear, cubic-bezier(n1, n2, n3, n4) */
/* Examples: */
animate: spin 2s ease-in;
animation-timing-function: cubic-bezier(0.1, -0.6, 0.2, 0);
Iteration Count
Syntax Example
/* The iteration count is a number of times the animation should run from start to finish before stopping */
/* This property also accepts the keyword "infinite" for animations that won't stop running */
animation-iteration-count: number;
animation-iteration-count: 2;
animate: grow 2s infinite;
Animation Direction
Syntax Example
/* Available Settings: */
normal, reverse, alternate, alternate-reverse
animation-direction: reverse;
animation: spin 2s ease-in-out 1s infinite alternate;
Transitions & Transition Timing Functions
Transitions are very helpful for making the change between a hover state and a normal state more smooth, but can be used for other purposes as well. They are simple to add to CSS and improve interaction.
Transition on Hover
Syntax Example
a{
background-color: blue;
transition: background-color 2s;
}
a:hover{
background-color: green;
}
Link Text
Another Transition
Link TextTransformations
A CSS transformation does just what it sounds like it does. Use this property to move, scale, rotate, or otherwise alter the appearance of your elements. These can be combined with animations and/or transitions as well.