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

PropertyMeaning
transition-propertyWhat to animate, like background or all
transition-durationHow long, like 0.3s
transition-timing-functionease, linear, ease-in, ease-out
transition-delayWait 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 propertyMeaning
animation-nameName of the keyframes
animation-durationTime for one run
animation-iteration-countNumber of runs, or infinite
animation-delayWait before the start
animation-directionnormal, reverse, alternate
animation-fill-modeKeep 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 transition for a smooth change between two states.
  • Use @keyframes and animation for repeating or multi-step effects.
  • Prefer transform and opacity.
  • Next: CSS Media Queries.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.