CSS Animations Explained

Learn CSS animation fundamentals, transitions, keyframes, and performance optimization techniques.

🎯 Introduction

Animation is an important part of the modern web experience. CSS lets you change button colors on hover, move elements smoothly, and create complex loading indicators, making pages more engaging and interactive. This article walks through animation fundamentals and performance techniques to help you build smooth web animations.


🧷 Interactive Effects: Pseudo-Class Selectors

Interactive animation starts with a trigger, and pseudo-class selectors are useful for this. Common pseudo-classes include:

Pseudo-classWhen it applies
:hoverWhile a pointing device hovers over an element
:focusWhen an element has focus
:activeWhile an element is being activated, such as during a mouse press
:checkedWhen a supported form control is checked or selected

For example, make a button's background red on hover:

button:hover {
    background-color: red;
}
Pseudo-classes commonly trigger CSS effects. Combine them with transitions or animations to provide interactive feedback.

🌀 Transitions: transition

Transitions are useful for simple animations that smoothly interpolate between two states. Their core properties include:

PropertyDescription
transition-propertySpecifies which properties to transition
transition-durationSets how long the transition takes
transition-timing-functionControls the rate of change over time
transition-delaySets the delay before the transition starts

This example smoothly changes a button's background color over 0.5 seconds:

button {
    background-color: blue;
    transition: background-color 0.5s ease;
}

button:hover {
    background-color: orange;
}

On hover, the background transitions to orange; when the pointer leaves, it returns to blue.

Use transitions for changes between states, such as button colors or opacity.

🎬 Animation Basics: animation and @keyframes

Animations suit more complex effects, such as multi-stage changes and repeating sequences. They have two parts:

  • @keyframes defines the animation's keyframes: property values at different stages.
  • The animation properties control playback.

Key properties include:

PropertyPurpose
animation-nameNames the keyframe animation to use
animation-durationSets the animation duration
animation-timing-functionControls the rate of change over time
animation-delaySets the delay before playback
animation-iteration-countSets the number of repetitions
animation-directionSets the playback direction

Here is a simple flashing color animation:

@keyframes flash {
    0% {
        background-color: yellow;
    }
    50% {
        background-color: red;
    }
    100% {
        background-color: yellow;
    }
}

button {
    animation-name: flash;
    animation-duration: 2s;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
}

The button repeatedly changes between yellow and red.

Use animations for complex, multi-stage, or repeating effects.

🛠️ Animation Performance: Combine transform and transition

Efficient animations improve the user experience without slowing down the page. General guidelines include:

  • Avoid animating layout properties directly, such as width, height, margin, and padding.
  • Prefer transform and opacity, which can benefit from GPU-accelerated compositing.

Use transform with transition for effects such as translation, scaling, and rotation:

button {
    transition: transform 0.3s ease;
}

button:hover {
    transform: translateY(-5px) scale(1.1);
}

This can keep the animation on the compositing stage without triggering layout, improving performance.

Avoid frequent changes to properties that trigger layout calculations, as they can make animations stutter.

🔍 Understanding Reflow and Repaint

Animation performance depends closely on how the browser renders a page.

Rendering stageDescriptionExample triggers
Reflow (layout)Recalculates page geometryChanges to element dimensions or positioning
RepaintUpdates visual appearance without changing layoutChanges to text or background colors

Avoiding reflow is especially important for animation. Transform and opacity do not require layout recalculation and can often be handled by compositing, making them efficient choices.

Understanding reflow and repaint helps you write more efficient animation code.

❓ Knowledge Check

Q1: How do transition and animation differ? Transitions handle simple changes between states. Animations support complex, multi-stage sequences and repeated playback.

Q2: Why avoid animating width and height? Changing these properties triggers layout recalculation, which can reduce performance.

Q3: How can you make animations smoother? Prefer transform and opacity, avoid triggering layout, and take advantage of GPU-accelerated compositing.


🧪 Exercises

Exercise 1: Smoothly Change a Button's Color on Hover

Create a button whose background transitions from blue to green on hover over 0.4 seconds.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Button Color Animation</title>
        <style>
            button {
                background-color: blue;
                color: white;
                padding: 12px 24px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                transition: background-color 0.4s ease;
            }
            button:hover {
                background-color: green;
            }
        </style>
    </head>
    <body>
        <button>Hover to Change Color</button>
    </body>
</html>

Copy the code into your editor and preview the result!


Exercise 2: Create an Infinite Rotation Animation

Make an element rotate continuously, completing one turn every 3 seconds.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Rotation Animation</title>
        <style>
            @keyframes spin {
                0% {
                    transform: rotate(0deg);
                }
                100% {
                    transform: rotate(360deg);
                }
            }
            .spinner {
                width: 100px;
                height: 100px;
                background-color: #f39c12;
                margin: 50px auto;
                border-radius: 50%;
                animation: spin 3s linear infinite;
            }
        </style>
    </head>
    <body>
        <div class="spinner"></div>
    </body>
</html>

Copy the code into your editor and preview the result!


🎉 You have learned CSS animation basics, how pseudo-classes trigger effects, the difference between transitions and animations, and techniques for efficient animation. Keep practicing to build even more engaging effects!