CSS Animations

CSS animations enable developers to create dynamic and interactive web experiences by allowing elements to change styles over time. They enhance user engagement and can be used to draw attention to important elements, provide visual feedback, or simply add flair to a design.

1. Introduction to CSS Animations

CSS animations allow elements to transition between styles smoothly over a specified duration. Unlike transitions, which occur in response to user interactions, animations can run automatically, repeat, and have multiple keyframes defining various states throughout the animation sequence.

2. Syntax of CSS Animations

CSS animations are defined using the @keyframes rule, which specifies the changes in styles at various stages of the animation. These animations are then applied to elements using the animation property or its sub-properties.

3. @keyframes Rule

The @keyframes rule defines the intermediate steps in an animation sequence by establishing keyframes, which are points in the animation timeline where specific styles are applied.


/* Define keyframes for a bounce animation */
@keyframes bounce {
    0%   { transform: translateY(0); }
    50%  { transform: translateY(-30px); }
    100% { transform: translateY(0); }
}
        

<!-- Apply the 'bounce' animation to a div -->
<div class="output">
    <div class="box bounce" style="animation: bounce 2s infinite;"></div>
</div>
        

This bounce animation moves the element upward by 30 pixels at the 50% mark and then returns it to its original position, creating a continuous bouncing effect.

4. Animation Properties

CSS provides several properties to control the behavior of animations. These can be combined using the shorthand animation property or specified individually.

animation-name: Specifies the name of the @keyframes animation.
animation-duration: Defines how long the animation takes to complete one cycle.
animation-timing-function: Describes how the animation progresses over its duration (e.g., linear, ease-in, ease-out).
animation-delay: Sets a delay before the animation starts.
animation-iteration-count: Determines how many times the animation should repeat.
animation-direction: Specifies whether the animation should play forwards, backwards, or alternate.
animation-fill-mode: Defines how the animation applies styles before and after its execution.
animation-play-state: Controls whether the animation is running or paused.

5. Basic Animation Examples

Below are several fundamental examples of CSS animations demonstrating different effects and properties.


a. Fade In Animation


/* Define keyframes for fade-in */
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

/* Apply fade-in animation */
.fade-in {
    animation: fadeIn 3s ease-in forwards;
}
        

<!-- Apply 'fade-in' animation to a paragraph -->
<div class="output">
    <p class="fade-in" style="opacity: 0;">This paragraph fades in over 3 seconds.</p>
</div>
        

This paragraph fades in over 3 seconds.

The fadeIn animation smoothly transitions the paragraph's opacity from 0 to 1, making it appear gradually.


b. Slide In Animation


/* Define keyframes for slide-in */
@keyframes slideIn {
    from { transform: translateX(-100%); }
    to { transform: translateX(0); }
}

/* Apply slide-in animation */
.slide-in {
    animation: slideIn 1s ease-out forwards;
}
        

<!-- Apply 'slide-in' animation to a div -->
<div class="output">
    <div class="box slide-in" style="
        transform: translateX(-100%);
    "></div>
</div>
        

The slideIn animation moves the div from the left side of its container into view, creating a sliding effect.


c. Bounce Animation


/* Define keyframes for bounce */
@keyframes bounce {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-30px); }
}

/* Apply bounce animation */
.bounce {
    animation: bounce 2s infinite;
}
        

<!-- Apply 'bounce' animation to a button -->
<div class="output">
    <button class="bounce" style="
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        background-color: #ff6347;
        color: #fff;
        cursor: pointer;
    ">Bouncing Button</button>
</div>
        

The bounce animation creates a bouncing effect by moving the button upward and then returning it to its original position repeatedly.


d. Rotating Animation


/* Define keyframes for rotation */
@keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

/* Apply rotation animation */
.rotate {
    animation: rotate 4s linear infinite;
}
        

<!-- Apply 'rotate' animation to an icon -->
<div class="output">
    <div class="box rotate" style="
        background-color: #1e90ff;
    "></div>
</div>
        

The rotate animation spins the element continuously, making it rotate 360 degrees over 4 seconds in a linear motion.


e. Color Change Animation


/* Define keyframes for color change */
@keyframes colorChange {
    0% { background-color: #ff7e5f; }
    50% { background-color: #feb47b; }
    100% { background-color: #ff7e5f; }
}

/* Apply color change animation */
.color-change {
    animation: colorChange 3s ease-in-out infinite;
}
        

<!-- Apply 'color-change' animation to a div -->
<div class="output">
    <div class="box color-change"></div>
</div>
        

The colorChange animation smoothly transitions the background color of the div from coral to peach and back, creating a pulsating effect.

6. Advanced Animation Examples

Advanced animations involve combining multiple animations, using animation delays, controlling the animation sequence, and integrating with JavaScript for dynamic interactions.


a. Complex Multi-step Animation


/* Define keyframes for multi-step animation */
@keyframes multiStep {
    0% { transform: scale(1); background-color: #ff7e5f; }
    25% { transform: scale(1.2); background-color: #feb47b; }
    50% { transform: scale(1); background-color: #6a11cb; }
    75% { transform: scale(1.2); background-color: #2575fc; }
    100% { transform: scale(1); background-color: #1e3c72; }
}

/* Apply multi-step animation */
.multi-step {
    animation: multiStep 5s ease-in-out infinite;
}
        

<!-- Apply 'multi-step' animation to a div -->
<div class="output">
    <div class="box multi-step"></div>
</div>
        

The multiStep animation scales the div up and down while changing its background color through several stages, creating a dynamic and engaging effect.


b. Hover-triggered Animation


/* Define keyframes for hover animation */
@keyframes hoverGrow {
    from { transform: scale(1); }
    to { transform: scale(1.1); }
}

/* Apply hover animation */
.hover-grow:hover {
    animation: hoverGrow 0.3s forwards;
}
        


<div class="output">
    <button class="hover-grow" style="
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        background-color: #20b2aa;
        color: #fff;
        cursor: pointer;
    ">Hover to Grow</button>
</div>
        

When the user hovers over the button, it slightly enlarges, providing immediate visual feedback.


c. Animation with JavaScript Triggers


/* Define keyframes for shake */
@keyframes shake {
    0% { transform: translateX(0); }
    25% { transform: translateX(-5px); }
    50% { transform: translateX(5px); }
    75% { transform: translateX(-5px); }
    100% { transform: translateX(0); }
}

/* Apply shake animation */
.shake {
    animation: shake 0.5s;
}
        

<!-- Apply 'shake' animation to an input field on button click -->
<div class="output">
    <input type="text" id="shake-input" placeholder="Shake me!" style="
        padding: 10px;
        border: 2px solid #ccc;
        border-radius: 5px;
    ">
    <button onclick="document.getElementById('shake-input').classList.add('shake');" style="
        padding: 10px 20px;
        margin-left: 10px;
        border: none;
        border-radius: 5px;
        background-color: #ff6347;
        color: #fff;
        cursor: pointer;
    ">Shake Input</button>
</div>
        

Clicking the "Shake Input" button adds the shake class to the input field, triggering the shake animation defined in the CSS.


d. Loading Spinner Animation


/* Define keyframes for spinner */
@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

/* Spinner styles */
.spinner {
    border: 8px solid #f3f3f3;
    border-top: 8px solid #3498db;
    border-radius: 50%;
    width: 60px;
    height: 60px;
    animation: spin 2s linear infinite;
}
        

<!-- Display spinner -->
<div class="output">
    <div class="spinner"></div>
</div>
        

The spinner class creates a rotating loader, commonly used to indicate loading states in applications.


e. Sequential Animations


/* Define keyframes for fade-in */
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

/* Define keyframes for move-up */
@keyframes moveUp {
    from { transform: translateY(20px); }
    to { transform: translateY(0); }
}

/* Apply sequential animations */
.sequential-anim {
    animation: fadeIn 1s ease-out forwards, moveUp 1s ease-out forwards;
    animation-delay: 0s, 1s;
}
        

<!-- Apply sequential animation to a div -->
<div class="output">
    <div class="box sequential-anim" style="
        opacity: 0;
        transform: translateY(20px);
    "></div>
</div>
        

The sequential-anim class first fades in the div over 1 second, then moves it upward over the next second, creating a smooth two-step animation.

7. Best Practices

Adhering to best practices ensures that your CSS animations are smooth, performant, and enhance the user experience without causing distractions or performance issues.

Use Animations Purposefully: Ensure that animations serve a clear purpose, such as providing feedback or enhancing aesthetics.
Keep Animations Simple: Avoid overly complex animations that can overwhelm users or negatively impact performance.
Consider Accessibility: Provide options to disable animations for users who may experience discomfort or have motion sensitivities.
Optimize Performance: Use hardware-accelerated properties like transform and opacity to ensure smooth animations.
Test Across Devices: Ensure that animations perform well on various devices and screen sizes.
Use Animation Libraries Wisely: While libraries can simplify animations, ensure they do not bloat your project unnecessarily.

a. Use Animations Purposefully

Animations should enhance the user experience by providing feedback or guiding attention, not merely for decoration.


/* Subtle hover animation for buttons */
.button-animated {
    transition: background-color 0.3s, transform 0.3s;
}

.button-animated:hover {
    background-color: #3498db;
    transform: scale(1.05);
}
        

<!-- Apply 'button-animated' to a button -->
<div class="output">
    <button class="button-animated" style="
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        background-color: #2980b9;
        color: #fff;
        cursor: pointer;
        transition: background-color 0.3s, transform 0.3s;
    ">Hover Me</button>
</div>
        

In this example, the button subtly changes color and slightly enlarges on hover, providing clear feedback without being distracting.


b. Keep Animations Simple


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

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

<!-- Apply 'pulse' animation to a div -->
<div class="output">
    <div class="box pulse" style="
        animation: pulse 1.5s ease-in-out infinite;
    "></div>
</div>
        

The pulse animation creates a gentle scaling effect, making the element subtly grow and shrink, drawing attention without overwhelming the user.


c. Consider Accessibility


/* Disable animations for users who prefer reduced motion */
@media (prefers-reduced-motion: reduce) {
    .animation {
        animation: none;
        transition: none;
    }
}
        

<!-- Apply 'animation' class to a div -->
<div class="output">
    <div class="box animation" style="
        animation: rotate 4s linear infinite;
    "></div>
</div>
        

Using the @media (prefers-reduced-motion) query ensures that animations respect user preferences, enhancing accessibility for users with motion sensitivities.


d. Optimize Performance


/* Smooth and performant animation */
@keyframes move {
    from { transform: translateX(0); }
    to { transform: translateX(100px); }
}

.move {
    animation: move 2s ease-in-out infinite alternate;
}
        

<!-- Apply 'move' animation to a div -->
<div class="output">
    <div class="box move" style="
        animation: move 2s ease-in-out infinite alternate;
    "></div>
</div>
        

The move animation translates the div horizontally, smoothly moving it back and forth without causing layout shifts or jank, ensuring optimal performance.

8. Browser Compatibility and Fallbacks

While modern browsers support CSS animations, it's crucial to ensure compatibility and provide fallbacks for older browsers to maintain a consistent user experience.


/* Fallback for older browsers */
.animation-fallback {
    /* Fallback solid color */
    background-color: #3498db;
    /* CSS animation */
    animation: rotate 4s linear infinite;
}

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

<!-- Apply 'animation-fallback' to a div -->
<div class="output">
    <div class="animation-fallback" style="
        background-color: #3498db;
        animation: rotate 4s linear infinite;
        height: 100px;
        width: 100px;
        border-radius: 50%;
        margin: 0 auto;
    "></div>
</div>
        

By specifying a fallback background-color, browsers that do not support animations will display the solid color instead of leaving the element unstyled.

9. Conclusion

CSS animations are powerful tools that can significantly enhance the interactivity and visual appeal of your web projects. By understanding the fundamentals, leveraging keyframes, and applying best practices, you can create engaging animations that improve user experience.

Remember to use animations purposefully, keep them simple and performant, consider accessibility, and ensure compatibility across different browsers and devices. With these guidelines, CSS animations can be a valuable addition to your web design toolkit.

Back to Table of Contents

Previous: CSS Gradients

<