Understanding CSS Animations and Transitions

Mar 9, 2025

CSS Animations and Transitions

Overview

  • Two primary ways to create animations in CSS: Transitions and Animations.

Transitions

  • Definition: Smooth changes in CSS properties over time.
  • When to Use: Ideal for interactive property changes (e.g., hover, focus).
  • Example: Button moves 10 pixels up when hovered.
  • Key Properties:
    • transition-property: Defines which property to apply the transition to.
    • transition-duration: Duration of the transition (e.g., 0.3 seconds).
    • transition-timing-function: Acceleration curve (e.g., ease, linear).
    • transition-delay: Delay before transition starts (usually 0 seconds).
  • Shorthand Property: Can combine properties using transition.

Animations

  • Definition: More complex animations utilizing keyframes.
  • When to Use: Used for more complex animations that do not rely on property changes.
  • Key Properties:
    • @keyframes: Define the start and end points of the animation.
    • Animation properties: Include animation-name, duration, timing function, delay, iteration count, direction, and fill mode.
  • Example: An H1 element sliding in from the left.

Creating Transitions

  1. Define a component (e.g., a button).
  2. Set up CSS styles and a hover state.
  3. Add transition properties:
    • Example: transition: transform 0.3s ease 0s;
  4. Multiple Properties: Use comma separation or the all keyword to apply transitions to multiple properties.

Creating Animations

  1. Create a keyframe animation using @keyframes.
  2. Define the start (from) and end (to) states of the animation.
  3. Apply animation properties to the element.
    • Example:
      • animation-name: Name of the keyframe.
      • animation-duration: Duration of animation.
      • animation-timing-function: Same options as transitions.
      • animation-iteration-count: Number of times to run the animation.
      • animation-direction: Normal or reverse.
      • animation-fill-mode: How styles are applied before/after animation.
  4. Use shorthand property for cleaner code.

Utility Class Architecture

  • Create utility classes for better reusability of animations.
  • Example Classes:
    • .animate { animation-duration: 1s; animation-fill-mode: both; }
    • Variants for infinite, delay, fast, and slow animations.
  • Decoupling Animation from Elements: Helps avoid redundancy and maintain clean code.

Additional Animations

  • Create additional animations by modifying keyframes.
    • Example: Create a rotate animation or a bounce animation.
  • Keyframe Control: Use percentages for more control and avoid repeating properties.

Conclusion

  • Understanding transitions and animations opens creativity for building visuals.
  • Encourage experimentation with various animation properties and utility classes.