Course Content
CSS Tutorial
About Lesson

CSS animations (keyframes, animation properties)

Cascading Style Sheets (CSS) animations add dynamic and engaging visual effects to web elements, enhancing user experience. By utilizing keyframes and animation properties, developers can create captivating animations that bring websites and applications to life.

Keyframes in CSS Animations

Keyframes define specific stages of an animation’s timeline. They allow developers to specify the style changes that occur at various points during the animation. Keyframes are declared using the @keyframes rule followed by a name that identifies the animation sequence. Within the keyframes, different percentages (from 0% to 100%) indicate the progression of the animation and the styles applied at each stage.

@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}

In this example, the fadeIn animation gradually increases the opacity of an element from 0% to 100%, creating a smooth fade-in effect.

Animation Properties in CSS

Once keyframes are defined, they can be applied to elements using animation properties. These properties include:

  • animation-name: Specifies the name of the keyframe animation to be applied.
  • animation-duration: Sets the duration of the animation.
  • animation-timing-function: Defines the speed curve of the animation (easing functions like ease-in, ease-out, linear, etc.).
  • animation-delay: Determines a delay before the animation starts.
  • animation-iteration-count: Specifies the number of times the animation should repeat.
  • animation-direction: Controls whether the animation plays forward, backward, or alternates direction.
.element {
animation-name: fadeIn;
animation-duration: 2s;
animation-timing-function: ease-in-out;
animation-delay: 0.5s;
animation-iteration-count: 3;
animation-direction: alternate;
}

Here, the .element will undergo the fadeIn animation with a duration of 2 seconds, easing in and out, starting after a delay of 0.5 seconds, repeating three times, and alternating direction.

Best Practices for CSS Animations

  • Performance Optimization: Keep animations lightweight to prevent performance issues, especially on mobile devices.
  • Browser Compatibility: Check compatibility across different browsers and use vendor prefixes when necessary (-webkit-, -moz-, -o-, -ms-).
  • Subtle and Purposeful Animations: Use animations judiciously to enhance user experience without overwhelming or distracting visitors