Translate

Tuesday 11 September 2018

How to Get Started with CSS Animation

The following is a short extract from Tiffany's upcoming book, CSS Master, 2nd Edition, which will be available shortly.

Think of CSS animation as the more sophisticated sister to CSS transitions. Animations differ from transforms in a few key ways:

  • Animations don’t degrade gracefully. If there’s no support from the browser, the user is out of luck. The alternative is to use JavaScript.
  • Animations can repeat, and repeat infinitely. Transitions are always finite.
  • Animations use keyframes, which offer the ability to create more complex and nuanced effects.
  • Animations can be paused in the middle of the play cycle.

The latest versions of all major browsers support CSS animations. Firefox versions 15 and earlier require a -moz- prefix; later version don’t. Internet Explorer versions 10 and 11 also support animations without a prefix, as do all versions of Microsoft Edge.

We can check for CSS animations support in a few ways. The first is by testing for the presence of CSSKeyframeRule as a method of the window object:

const hasAnimations = 'CSSKeyframeRule' in window;

If the browser supports the @supports rule and CSS.supports() API, we can use that instead:

const hasAnimations = CSS.supports('animation-duration: 2s');

As with transitions, we can only animate interpolatable values such as color values, lengths, and percentages.

Creating Your First Animation

We first have to define an animation using an @keyframes rule. The @keyframes rule has two purposes:

  • setting the name of our animation
  • grouping our keyframe rules

Let’s create an animation named pulse:

@keyframes pulse {

}

Our keyframes will be defined within this block. In animation, a keyframe is a point at which the action changes. With CSS animations specifically, keyframe rules are used to set property values at particular points in the animation cycle. Values that fall between the values in a keyframe rule are interpolated.

At the minimum, an animation requires two keyframes: a from keyframe, which is the starting state for our animation, and a to frame, which is its end state. Within each individual keyframe block, we can define which properties to animate:

@keyframes pulse {
    from {
        transform: scale(0.5);
        opacity: .8;
    }

    to {
        transform: scale(1);
        opacity: 1;
    }
}

This code will scale our object from half its size to its full size, and change the opacity from 80% to 100%.

The keyframes rule only defines an animation, though. By itself, it doesn’t make elements move. We need to apply it. Let’s also define a pulse class that we can use to add this animation to any element:

.pulse {
    animation: pulse 500ms;
}

Here, we’ve used the animation shorthand property to set the animation name and duration. In order for an animation to play, we need the name of an @keyframes rule (in this case, pulse) and a duration. Other properties are optional.

The order of properties for animation is similar to that of transition. The first value that can be parsed becomes the value of animation-duration. The second value becomes the value for animation-delay. Words that aren’t CSS-wide keywords or animation property keyword values are assumed to be @keyframe ruleset names.

As with transition, animation also accepts an animation list. The animation list is a comma-separated list of values. We could, for example, split our pulse animation into two rules—pulse and fade:

@keyframes pulse {
    from {
        transform: scale(0.5);
    }       
    to {
        transform: scale(1);
    }
}

@keyframes fade {
    from {
        opacity: .5;
    }
    to {
        opacity: 1;
    }
}

Then we could combine them as part of a single animation:

.pulse-and-fade {
    animation: pulse 500ms, fade 500ms;
}

Animation Properties

Though using the animation property is shorter, sometimes longhand properties are clearer. Longhand animation properties are listed below:

Property Description Initial value
animation-delay How long to wait before executing the animation 0s (executes immediately)
animation-duration How long the cycle of an animation should last 0s (no animation occurs)
animation-name The name of an @keyframes rule none
animation-timing-function How to calculate the values between the start and end states ease
animation-iteration-count How many times to repeat the animation 1
animation-direction Whether or not the animation should ever play in reverse normal (no reverse)
animation-play-state Whether the animation is running or paused running
animation-fill-mode Specifies what property values are applied when the animation isn’t running none

The animation-delay and animation-duration properties function like transition-delay and transition-duration. Both accept time units as a value, either in seconds (s) or milliseconds (ms). Negative time values are valid for animation-delay, but not animation-duration.

Let’s rewrite our .pulse ruleset using longhand properties. Doing so gives us the following:

.pulse {
    animation-name: pulse;
    animation-duration: 500ms;
}

The animation-name property is fairly straightforward. Its value can be either none or the name of the @keyframes rule. Animation names have few restrictions. CSS keywords such as initial, inherit, default, and none are forbidden. Most punctuation characters won’t work, while letters, underscores, digits, and emojis (and other Unicode) characters usually will. For clarity and maintainability, it’s a good idea to give your animations descriptive names, and avoid using CSS properties or emojis as names.

To Loop or Not to Loop: The animation-iteration-count Property

If you’re following along with your own code, you’ll notice that this animation only happens once. We want our animation to repeat. For that, we’ll need the animation-iteration-count property.

The animation-iteration-count property accepts most numeric values. Whole numbers and decimal numbers are valid values. With decimal numbers, however, the animation will stop partway through the last animation cycle, ending in the to state. Negative animation-iteration-count values are treated the same as 1.

To make an animation run indefinitely, use the infinite keyword. The animation will play an infinite number of times. Of course, infinite really means until the document is unloaded, the browser window closes, the animation styles are removed, or the device shuts down. Let’s make our animation infinite:

.pulse {
    animation-name: pulse;
    animation-duration: 500ms;
    animation-iteration-count: infinite;
}

Or, using the animation shorthand property:

.pulse {
    animation: pulse 500ms infinite;
}

Playing Animations: the animation-direction Property

There’s still a problem with our animation, however. It doesn’t so much pulse as repeat our scaling-up animation. What we want is for this element to scale up and down. Enter the animation-direction property.

The post How to Get Started with CSS Animation appeared first on SitePoint.



No comments:

Post a Comment