intermediate css 14 min read

CSS Animations and Transitions

Create smooth animations and transitions with pure CSS.

css animations css transitions keyframes animate css

CSS Transitions

Transitions animate property changes smoothly.

Basic Syntax

.button {
    background: #3b82f6;
    transition: background 0.3s ease;
}

.button:hover {
    background: #2563eb;
}

Transition Properties

.element {
    transition-property: all;
    transition-duration: 0.3s;
    transition-timing-function: ease-in-out;
    transition-delay: 0s;

    /* Shorthand */
    transition: all 0.3s ease-in-out 0s;
}

Timing Functions

transition: all 0.3s linear;
transition: all 0.3s ease;
transition: all 0.3s ease-in;
transition: all 0.3s ease-out;
transition: all 0.3s ease-in-out;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

CSS Keyframe Animations

Basic Animation

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

.element {
    animation: fadeIn 0.5s ease forwards;
}

Multi-Step Animation

@keyframes bounce {
    0%, 100% {
        transform: translateY(0);
    }
    50% {
        transform: translateY(-20px);
    }
}

.bouncing {
    animation: bounce 1s ease infinite;
}

Animation Properties

.element {
    animation-name: fadeIn;
    animation-duration: 1s;
    animation-timing-function: ease;
    animation-delay: 0s;
    animation-iteration-count: 1;
    animation-direction: normal;
    animation-fill-mode: forwards;
    animation-play-state: running;

    /* Shorthand */
    animation: fadeIn 1s ease 0s 1 normal forwards running;
}

Common Animation Examples

Pulse Effect

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

.pulse {
    animation: pulse 2s ease infinite;
}

Slide In

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

.slide-in {
    animation: slideIn 0.5s ease forwards;
}

Spinner

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

.spinner {
    width: 40px;
    height: 40px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #3b82f6;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

Performance Tips

  1. Animate only transform and opacity for smooth performance
  2. Use will-change sparingly for complex animations
  3. Prefer CSS animations over JavaScript when possible
  4. Use prefers-reduced-motion media query
@media (prefers-reduced-motion: reduce) {
    * {
        animation-duration: 0.01ms !important;
        transition-duration: 0.01ms !important;
    }
}

Best Practices

  1. Keep animations subtle and purposeful
  2. Use appropriate timing (0.2-0.5s for most UI)
  3. Test on different devices
  4. Consider accessibility

Related: CSS Transforms Guide

Related Tools

Continue Learning