How to use CSS Animations without a library

Web animations breathe life into websites, captivating users and enhancing overall design. While animation libraries provide convenience, understanding the fundamentals of pure CSS animations unlocks customization and control over your website’s visual flair. Let’s dive into the world of library-free CSS animations!

The Basics: @keyframes and ‘animation’

  1. @keyframes: Think of this as your animation blueprint. It allows you to define the styling changes throughout the animation sequence.

    CSS
    @keyframes fadeAndSlide {
      0% { opacity: 0; transform: translateY(20px);}
      100% { opacity: 1; transform: translateY(0);}
    }
    
  2. animation: This property is where you put your animation plan into action. Here’s what the key parts mean:

    CSS
    .animated-element {
      animation-name: fadeAndSlide; 
      animation-duration: 2s;        
      animation-timing-function: ease-in; 
      animation-iteration-count: 2;  
      animation-direction: alternate; 
    }
    
    • animation-name: Connects to your @keyframes.
    • animation-duration: How long the animation runs.
    • animation-timing-function: Pace of the animation (e.g., ease-in, linear).
    • animation-iteration-count: How many times it repeats (infinite for looping).
    • animation-direction: Allows for reverse or alternating playback.

Common Animation Techniques

  • Fading: Play with the opacity property for subtle transitions.
  • Movement: Use transform: translate() to shift elements across the screen.
  • Scaling: Use transform: scale() to make elements grow or shrink.
  • Rotation: Explore transform: rotate() to add a spin.
  • Color Changes: Animate background-color or color for eye-catching effects.

Example: A Pulsing Button

HTML
<button class="pulse-button">Click Me</button>
CSS
.pulse-button {
  /* Regular button styling here */
}

@keyframes pulse {
  0% { transform: scale(1); } 
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.pulse-button:hover { 
  animation: pulse 1s infinite alternate;
} 

Beyond the Basics

  • Transitions: Use the transition property for smoother changes between states (like on hover).
  • Animation Events: JavaScript lets you listen for events like ‘animationstart’ and ‘animationend’ for additional control.
  • Scroll-triggered Animations: Use the IntersectionObserver API to start animations as elements come into view.

Benefits of Library-Free CSS Animations

  • Granular Control: Tailor animations exactly to your design needs.
  • Smaller File Sizes: Avoid the overhead of external libraries.
  • Learning Opportunity: Deepen your CSS knowledge and skills.

Let Your Creativity Flow!

Pure CSS animations are a fantastic tool for web developers. Get experimenting, be creative, and remember, resources like MDN (https://developer.mozilla.org/) are always there for in-depth reference.