Color scheme

Keyframes and Reduced Motion

CSS transitions animate between two states and let the browser decide when to run. Keyframe animations hand full control to you: you define every step of the motion, how many times it plays, whether it reverses, and what happens before and after it runs. That power comes with more responsibility, particularly around accessibility. This activity covers the mechanics of @keyframes, the animation shorthand, iteration and direction patterns, compositor-friendly property choices, and a deeper look at prefers-reduced-motion as it applies to complex and infinite animations.

Defining Keyframes

A keyframe animation starts with an @keyframes rule that gives the animation a name and defines its steps. Each step is a percentage (or the keywords from and to) representing a point in the animation's duration, paired with the CSS property values that should apply at that moment. The browser interpolates smoothly between each defined step.


    /* from/to are aliases for 0% and 100% */
    @keyframes fade-in {
        from { opacity: 0; }
        to   { opacity: 1; }
    }

    /* Multiple stops with percentage values */
    @keyframes bounce {
        0%   { transform: translateY(0); }
        40%  { transform: translateY(-30px); }
        60%  { transform: translateY(-20px); }
        80%  { transform: translateY(-10px); }
        100% { transform: translateY(0); }
    }

You can list multiple percentages on one keyframe block when the same values apply at more than one point. This is useful for a pause in the middle of a loop or for a held position:


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

Keyframe names are case-sensitive identifiers. Use lowercase kebab-case names that describe the motion, not the element (slide-in not nav-animation). Descriptive motion names make keyframes reusable across different elements and easier to scan in a stylesheet.

The Animation Shorthand

The animation property combines eight sub-properties. The order follows the same duration-before-delay rule as transition, but there are more values to manage:

  • animation-name: The name of the @keyframes rule to apply.
  • animation-duration: How long one cycle of the animation takes.
  • animation-timing-function: The easing curve for each step (same options as transition-timing-function).
  • animation-delay: How long to wait before the first cycle begins. Negative values start the animation mid-cycle.
  • animation-iteration-count: How many times the animation runs. Accepts a number or infinite.
  • animation-direction: Whether the animation plays forward, backward, or alternates. Covered in the next section.
  • animation-fill-mode: What property values apply before the animation starts and after it ends.
  • animation-play-state: Whether the animation is running or paused. Useful for toggling with JavaScript.

    /* name | duration | easing | delay | iterations | direction | fill-mode */
    .element {
        animation: fade-in 400ms ease-out 0ms 1 normal forwards;
    }

    /* Shorthand can omit defaults; this is equivalent */
    .element {
        animation: fade-in 400ms ease-out forwards;
    }

animation-fill-mode

Fill mode is the sub-property that trips up students most often. By default, an animation has no effect before it starts or after it ends: the element snaps back to its original styles the moment the animation finishes. Fill mode changes that behavior:

  • none: Default. The element uses its normal styles before and after the animation.
  • forwards: After the animation ends, the element keeps the styles from the last keyframe. Use this when an animation is meant to permanently change an element's appearance, like a fade-in that should leave the element visible.
  • backwards: Before the animation starts (during the delay), the element uses the styles from the first keyframe. Useful when you want an element to start invisible even before a delayed fade-in begins.
  • both: Applies both forwards and backwards behavior simultaneously.

    /* Without forwards: element snaps back to opacity: 1 after animating */
    @keyframes fade-out {
        to { opacity: 0; }
    }

    /* With forwards: element stays hidden after the animation ends */
    .dismissing {
        animation: fade-out 300ms ease-in forwards;
    }

Iteration and Direction

Two sub-properties work together to control how an animation repeats: animation-iteration-count and animation-direction. Understanding both, and how they interact, gives you fine-grained control over looping motion.

Iteration Count

animation-iteration-count accepts any positive number (including decimals, which stop the animation partway through a cycle) or the keyword infinite for a loop that never stops. Use infinite loops deliberately: a loading spinner that runs while waiting for a network response is appropriate. A decorative background animation that loops forever without purpose is a distraction and a real problem for users with motion sensitivities.

Direction

animation-direction controls which way through the keyframes each cycle travels:

  • normal: Every cycle plays from 0% to 100%. Default.
  • reverse: Every cycle plays from 100% to 0%.
  • alternate: Odd cycles play forward (0% to 100%), even cycles play backward (100% to 0%). This creates a smooth back-and-forth loop without duplicating keyframes.
  • alternate-reverse: Same as alternate but starts with the backward pass.

The alternate direction is especially valuable for looping animations because it avoids a hard snap. Without it, a pulsing animation using normal direction jumps from 100% back to 0% at the start of each new cycle, creating a visible flicker. With alternate, the animation flows continuously in both directions.


    /* Without alternate: snaps back to scale(1) at the start of each loop */
    @keyframes pulse-bad {
        0%   { transform: scale(1); }
        100% { transform: scale(1.1); }
    }
    .pulse-bad {
        animation: pulse-bad 800ms ease-in-out infinite;
    }

    /* With alternate: flows smoothly back and forth */
    @keyframes pulse-good {
        from { transform: scale(1); }
        to   { transform: scale(1.1); }
    }
    .pulse-good {
        animation: pulse-good 800ms ease-in-out infinite alternate;
    }

Iteration and Direction in Action

The demo below animates the same keyframe with different iteration-count and direction values. Pay particular attention to the difference between normal infinite and alternate infinite: the snap at the loop boundary in the first case versus the smooth reversal in the second.

Normal Infinite
Alternate Infinite
Alternate-Reverse Infinite

Compositor-Friendly Properties

Not all CSS animations are created equal from a performance standpoint. When a property changes, the browser may need to do some or all of three types of work: recalculating layout, repainting pixels, and compositing layers. Each step is more expensive than the last, and triggering the earlier steps forces all the later ones to run too.

  • Layout: Changing a property like width, height, margin, top, or left forces the browser to recalculate how all affected elements are positioned and sized. This is the most expensive operation and can cause visible stuttering on complex pages.
  • Paint: Changing a property like background-color, border-color, or box-shadow requires the browser to redraw pixels in affected areas. More expensive than compositing, less expensive than layout.
  • Composite: Changing transform or opacity lets the browser move or fade already-painted layers without redrawing anything. This work happens on the GPU and runs independently of the main thread, which means it stays smooth even when the browser is busy doing other things.

The practical rule is straightforward: animate transform and opacity whenever possible. Moving something across the screen? Use translateX or translateY, not left or top. Showing or hiding something? Animate opacity, not display or visibility. Growing or shrinking something? Use scale, not width and height.

Compositor vs. Layout Animation

The demo below shows the same horizontal movement animated two ways: once with margin-left (which triggers layout recalculation on every frame) and once with transform: translateX() (which runs entirely on the compositor). On a fast machine the difference may be subtle, but on a slower device or a page under load, the layout-triggering animation will stutter noticeably while the transform animation stays smooth.

Layout Property: margin-left (Triggers Layout, Paint, and Composite)
Compositor Property: transform: translateX() (Composite Only)
Check the DevTools Performance Panel

Open Chrome DevTools, go to the Performance tab, and record while both animations are running. Look for the green compositor thread activity versus the main thread activity. You will see the transform animation barely touch the main thread while the margin-left animation generates layout recalculations on every frame. This is the clearest way to see the real cost difference.

will-change

The will-change property is a hint to the browser that an element is about to be animated, allowing it to promote the element to its own compositor layer in advance. This can eliminate the brief jank that sometimes occurs at the start of an animation before the browser has had time to set up the layer.


    .card {
        will-change: transform, opacity;
    }

Used correctly, will-change is a targeted fix for a specific observed performance problem. Used incorrectly, it makes things worse. Promoting an element to its own layer consumes GPU memory. If you apply will-change to every animated element by default, or leave it on elements that are not actively animating, you waste memory and can actually slow the page down. The pattern to follow is:

  • First, confirm there is an actual performance problem worth fixing. Do not add will-change preemptively.
  • Apply will-change shortly before the animation starts (via JavaScript or a parent hover state) and remove it immediately after the animation ends.
  • Limit it to the properties that will actually animate: will-change: transform, not will-change: all.
will-change Is a Last Resort

If animating only transform and opacity and the animation still stutters, then will-change may help. If you are animating layout-triggering properties and hoping will-change will fix the jank, it will not. The correct fix is to switch to compositor-friendly properties.

prefers-reduced-motion in Depth

The transitions activity introduced prefers-reduced-motion as a pattern. Keyframe animations demand a deeper treatment because they are far more likely to cause real harm. Infinite animations, rapid motion, and large-scale movement are all common in keyframe-based UI and are exactly what vestibular disorder sufferers and motion-sensitive users need to avoid.

Infinite Animations Are the Priority

A transition plays once and stops. An infinite keyframe animation plays for as long as the page is open. For a user with a vestibular disorder, a looping animation in peripheral vision can trigger symptoms the entire time they are on the page. This makes infinite animations the highest-priority target for reduced-motion handling. If an animation uses animation-iteration-count: infinite, it must have a prefers-reduced-motion override.


    .spinner {
        animation: spin 800ms linear infinite;
    }

    @media (prefers-reduced-motion: reduce) {
        .spinner {
            animation: none;
            /* Provide a static alternative so the loading state is still communicated */
            opacity: 0.5;
        }
    }

Scale Back Rather Than Remove When Possible

Removing motion entirely is always safe, but sometimes the animation communicates meaningful state: a progress indicator, a loading spinner, or a notification badge. In these cases, a reduced version that communicates the same information with less motion is better than nothing at all. A spinner that pulses slowly in opacity rather than rotating continuously conveys "loading" without the vestibular risk of spinning motion.


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

    @keyframes pulse-opacity {
        0%, 100% { opacity: 1; }
        50%       { opacity: 0.4; }
    }

    .spinner {
        animation: spin 800ms linear infinite;
    }

    @media (prefers-reduced-motion: reduce) {
        .spinner {
            animation: pulse-opacity 1.5s ease-in-out infinite;
        }
    }

The no-preference Containment Pattern

As introduced in the transitions activity, you can write all motion rules inside a no-preference query instead of overriding them inside a reduce query. For keyframe animations this pattern is especially clean because it keeps every @keyframes declaration and every animation property together in one block, making it impossible to accidentally leave an animation unguarded:


    /* All motion in one guarded block */
    @media (prefers-reduced-motion: no-preference) {
        @keyframes slide-up {
            from { transform: translateY(20px); opacity: 0; }
            to   { transform: translateY(0);    opacity: 1; }
        }

        .card-enter {
            animation: slide-up 300ms ease-out forwards;
        }

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

        .spinner {
            animation: spin 800ms linear infinite;
        }
    }

    /* Reduced alternative lives outside the guard */
    @media (prefers-reduced-motion: reduce) {
        .spinner {
            animation: pulse-opacity 1.5s ease-in-out infinite;
        }
    }
Pick One Pattern and Stick to It

Mixing both the reduce override pattern and the no-preference containment pattern in the same stylesheet creates confusion about which animations are guarded and which are not. Choose one approach for your project and apply it everywhere. Either approach is correct as long as it is consistent.

Scroll-Driven Animations

Scroll-driven animations link a keyframe animation's progress to the user's scroll position rather than to a time duration. Instead of playing over a fixed number of milliseconds, the animation advances as the user scrolls down and reverses as they scroll up. This enables effects like reading progress bars, parallax reveals, and scroll-triggered entrance animations without any JavaScript.


    @keyframes reveal {
        from { opacity: 0; transform: translateY(20px); }
        to   { opacity: 1; transform: translateY(0); }
    }

    .scroll-reveal {
        animation: reveal linear both;
        animation-timeline: scroll();
    }

The animation-timeline property replaces the time-based duration with a scroll container as the driver. scroll() references the nearest scrollable ancestor by default, or you can pass arguments to target a specific axis or element. The view() function is a related alternative that drives the animation based on how far an element has entered the viewport, which is more useful for entrance effects.

Browser Support: ~83% as of 2026

Scroll-driven animations are supported in Chrome, Edge, Safari 26+, and most mobile browsers, but Firefox has not yet implemented the feature. Global usage sits around 83%, which is high enough to use with a graceful fallback but not high enough to rely on without one. The shorthand form of animation-timeline embedded directly in the animation shorthand has lower support still (around 70%) so it is safer to declare animation-timeline separately. Always test in Firefox and ensure the experience is acceptable without the scroll-driven behavior.

Check Your Understanding

Apply what you have learned by working through this coding challenge. Write the CSS to produce the described animation behavior, then use the copy icon to copy your completed code and paste it as a prompt to your AI assistant for feedback.


        /*
         * Create a notification badge that pulses to draw attention.
         *
         * Requirements:
         * 1. Write a @keyframes rule called "badge-pulse" that scales
         *    the element from its normal size to 115% and back. Use
         *    only compositor-friendly properties.
         *
         * 2. Apply the animation to .badge so it loops indefinitely,
         *    runs for 900ms, uses ease-in-out, and flows smoothly
         *    without snapping at the loop boundary.
         *
         * 3. Write a prefers-reduced-motion block that scales back
         *    the animation to something less intense but still
         *    communicates that the badge is active. Do not simply
         *    remove all animation.
         */

    

Resources