CSS Animations

Mastering the art of dynamic web design

Bringing Your Webpages to Life with CSS Animations

CSS animations offer a powerful and efficient way to add engaging visual feedback and motion to your websites without relying on JavaScript for simple effects. From subtle transitions to complex sequences, CSS animations can significantly enhance user experience and visual appeal.

Understanding the Core Concepts

At the heart of CSS animations are two key properties:

@keyframes

This rule defines the different styles that an element will go through during an animation. You can specify an animation's starting point (0% or `from`) and ending point (100% or `to`), or break it down into multiple steps.

animation property

This is a shorthand property that allows you to set various animation-related properties in one declaration. Key sub-properties include:

Practical Examples

1. Hover Effects (using transition, a related concept)

While transition is not strictly an animation, it's fundamental for smooth state changes. Here's a simple hover effect:

.box-to-animate {
  transition: transform 0.5s ease-in-out, background-color 0.5s ease-in-out;
}

.box-to-animate:hover {
  transform: scale(1.1) rotate(5deg);
  background-color: #005a9e;
}

2. Fade Out Animation

An element that smoothly fades away:

.element-fade {
  animation: fadeOut 2s forwards;
}

@keyframes fadeOut {
  from { opacity: 1; }
  to { opacity: 0; }
}

3. Slide In Animation

An element sliding in from the left:

.element-slide {
  animation: slideInFromLeft 1.5s ease-out forwards;
}

@keyframes slideInFromLeft {
  from {
    transform: translateX(-100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

4. Pulsing Effect

A simple pulsing animation for emphasis:

.custom-animation {
  animation: pulse 2s infinite ease-in-out;
}

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

Advanced Techniques

Combine multiple animations, use animation-composition for more control, and explore the possibilities of animating SVG elements for even richer interactions.