CSS Transitions and Animations
CSS can change a style smoothly instead of suddenly. A transition animates between two states, and an animation can run many steps without any trigger.
Transitions
.btn {
background: #0073aa;
transition: background 0.3s ease, transform 0.3s ease;
}
.btn:hover {
background: #e91e63;
transform: scale(1.1);
}
The hover state of the button (the smooth change does not show here)
Button in its hover state
| Property | Meaning |
|---|---|
transition-property | What to animate, like background or all |
transition-duration | How long, like 0.3s |
transition-timing-function | ease, linear, ease-in, ease-out |
transition-delay | Wait before starting |
In the shorthand the order is: property, duration, timing function, delay.
Animations with @keyframes
First describe the steps with @keyframes, then attach the animation to an element.
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
.heart {
animation: pulse 1.2s ease-in-out infinite;
}
On your page this circle grows and shrinks again and again
| Animation property | Meaning |
|---|---|
animation-name | Name of the keyframes |
animation-duration | Time for one run |
animation-iteration-count | Number of runs, or infinite |
animation-delay | Wait before the start |
animation-direction | normal, reverse, alternate |
animation-fill-mode | Keep the end style with forwards |
Note:
Animate transform and opacity where you can. They are smooth and cheap for the browser. Animating width, height or top makes the page redraw and can feel slow.
Summary
- Use
transitionfor a smooth change between two states. - Use
@keyframesandanimationfor repeating or multi-step effects. - Prefer
transformandopacity. - Next: CSS Media Queries.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |