The Ultimate Guide to CSS Keyframes Animation

Adarsh M

Posted On: April 22, 2024

view count125246 Views

Read time35 Min Read

The saying “first impression is the last impression” holds true, especially for online user experience. According to Forbes, nearly 94% of a website’s initial impression is influenced by its web design.

With animations in Cascading Style Sheets (CSS), users receive feedback while navigating the site, like when they click a button or scroll down with a downward arrow animation. CSS keyframes animation, a technique that interpolates between styles, plays a crucial role in providing these dynamic transitions.

Thanks to the CSS @keyframes property, achieving such effects only requires a few lines of code. This enhances the overall user experience, making the website more engaging and visually appealing.

In this blog, we will delve deeper into CSS keyframes animation, exploring how they work and their practical applications.

Overview of CSS Animations

Having some cool transitions and eye-catching animations shows that CSS animations have been used for hooking the users.

Illustration depicting various CSS animations and transitions

CSS Transitions Example

CSS animations are the means by which we can animate the transition from one state of CSS properties to another. It provides a simpler way for creating the illusion of motion and interactivity. CSS animations are typically more efficient in terms of performance because they can be offloaded to the browser’s GPU. This allows for smoother animations with minimal impact on CPU usage.

Let’s now see an example of a simple CSS animation where the element undergoes various translations, transformations, etc.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

In the above example, you can observe a series of transformations, translations, and visual changes in the webpage. CSS animations open a door for creativity, allowing the use of several animation properties to create eye-catching user experiences.

Talking about browser compatibility, almost all modern browsers have good support for CSS animations.

Illustration showing various CSS animations and transformations on a webpage

Source

Even though CSS animations are compatible with most modern browsers, achieving smooth animations across various screen sizes and devices can be a nuanced task.

To thoroughly test your CSS animations across different browsers, versions, devices, and platforms, you can leverage the Real Time Testing feature provided by LambdaTest.

Real Time Testing feature provided by LambdaTest being demonstrated on various devices and browsers

LambdaTest Real Time Testing on Windows + Chrome

Testing on AI-powered test orchestration and execution platforms like LambdaTest can give you a better insight about how end users see your web application. You can test on a remote test lab of 3000+ real browsers and operating systems.

Subscribe to the LambdaTest YouTube Channel. Get the latest updates on various automation testing tutorials covering mobile app testing, real device cloud, and more.

Now, let’s delve deeper into the CSS keyframes animation.

Info Note

Test CSS keyframes animation across 3000+ real environments. Try LambdaTest Today!

What are CSS Keyframes Animation?

CSS animations consist of two fundamental components, animation styles and keyframes of the animation. These components work together to bring life and interactivity to web elements.

Let’s explore each of these components in-depth.

@keyframes Rule

The @keyframes rule allows you to specify a sequence of keyframes, each with its own set of CSS properties and values. These keyframes define the intermediate steps of an animation so that you can have better control over the animation at each timeline.

Here is a breakdown:

When you set an animation duration, you can segment the behavior of an element into different points along the timeline using percentage values. The percentage values (0%, 25%, 100%, etc., in this case) represent the progress of the animation, and you can add as many intermediate steps as needed.

CSS Animation With Respect to Duration

CSS Animation With Respect to Duration

Alternatively, in CSS keyframes animation, you have the option to use from and to keywords to specify the animation’s initial and final states concisely. The from keyword defines the animation’s starting point, while to keyword signifies its ending point, simplifying the control of CSS keyframes animation behavior.

Within each keyframe, you can specify CSS properties and values that define how an element should appear at that point in the animation. You can animate almost all the CSS properties, such as opacity, transform, color, and more, depending on your custom use case.

Between the CSS keyframes, the browser automatically interpolates the styles, ensuring a smooth transition between them. This interpolation creates the illusion of continuous motion.

Illustration demonstrating CSS keyframes animation with from and to keywords

You can also control keyframes animation with JavaScript, allowing you to trigger animations in response to user interactions or specific events like mouse movements.

JavaScript enables you to start, pause, or dynamically modify animations, opening the door to creating dynamic animations, such as mouse movement-based animations and more.

Here is how you can listen to a click event on an element to control the state of the animation.

JavaScript:

Let’s now discuss various CSS keyframes animation properties.

Animation Styles

Animation styles, also known as animation properties, define the overall behavior of the animation. These styles dictate various aspects of the animation, including its duration, timing function, delay, and more.

Here’s a breakdown of these CSS keyframes animation properties:

CSS Animation Properties Breakdown

CSS Animation Properties Breakdown

animation-name

The CSS property animation-name is used to indicate the specific animation to apply to an element. It can reference one or more @keyframes rules, which describe the animation’s behavior. You can specify multiple @keyframes rules by separating their names with commas.

Syntax:

In the above syntax, the animation-name property is set to myAnimation, which refers to a previously defined CSS @keyframes rule. In cases where the provided name doesn’t match any existing @keyframes rule, no properties will undergo animation.

Here is an example of using the same CSS keyframes animation for multiple elements.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

In the above example, you can see the skeleton loading animation that is being applied to various elements. Similarly, you can also have multiple animations for the same element by specifying the animation names, as well as the @keyframe rule for it.

You might have also noticed the use of another property called animation-duration here in the example. Let’s now look into that.

animation-duration

The animation-duration property defines the duration of time required for an animation to execute a full cycle, from its initial state to its final state and back to the beginning.

You can specify the animation-duration in either seconds (s) or milliseconds (ms). The value must be a non-negative number, and it’s essential to include the unit.

Syntax:

Here’s an example of three different loading CSS keyframes animation with varying durations.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

Spinning loaders animation demonstrating varying durations from 1 to 5 seconds

Each loader is a spinning animation with a different duration. The loader1 has a duration of 1 seconds, loader2 has a duration of 2 seconds, and so on. You can observe the varying speeds when viewing the webpage.

animation-timing-function

The animation-timing-function CSS property defines how an animation progresses through its keyframes over time. It specifies the pacing of the animation by determining the rate of change in the animated properties during each part of the animation cycle.

The animation-timing-function defines the speed curve, defining whether the animation begins slowly and accelerates, maintains a consistent speed, or follows a unique progression.

Syntax:

The timing functions represent the type of easing function you want to apply to the animation. The timing functions in CSS are:

  • linear: A linear easing function means that the animation progresses at a constant speed.
  • ease: A standard easing function that starts slow, speeds up in the middle, and slows down at the end for smooth transitions.
  • ease-in: An ease-in function means that it starts slow and gradually accelerates.
  • ease-out: An ease-out function means that it starts fast and gradually decelerates.
  • ease-in-out: An ease-in-out function that combines ease-in and ease-out behaviors.
  • cubic-bezier(<number>, <number>, <number>, <number>): A custom cubic-bezier easing function is defined by four numeric values between 0 and 1. These values control the acceleration and deceleration of the animation.
  • steps(<integer> [, <step-position>]): A step-based easing function with an integer value representing the number of discrete steps in the animation. You can also optionally specify the step position as start, end, or none to control when the step occurs.

Let’s now take an example and see how these animation timing functions work.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

You can see that all six boxes have the same animation named Movement but they all behave differently depending on the timing function.

Apart from the timing function, we can also set a delay to the animations, let’s now look into the animation-delay property.

animation-delay

The animation-delay property, as the name suggests, specifies the amount of time that an animation needs to wait before starting an animation. It accepts values in seconds(s) or milliseconds (ms).

The animation-delay property can also accept negative values. The negative value means that the animation will start before its scheduled start time. So, it will effectively appear as if the animation has already been in progress when it’s triggered.

Syntax:

Here’s an example that showcases the use of the animation-delay property to create a delayed animations for a group of elements:

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

We have three <div> elements with the class .fade-in, and each element has a delay set using the animation-delay property. The animation-delay creates a sequence where each element starts fading in after a specific delay, resulting in a staggered fade-in effect along with a translation in the +X direction

Thus, the animation-delay property can be used for creating animation sequences by staggering the start times of different animations.

animation-direction

The animation-direction property is used to determine how an animation should play. It controls the direction in which the animation progresses between its keyframes, such as forward or reverse. The animation-direction property is really useful for controlling the playback of CSS keyframes animation.

Syntax:

The animation-direction property accepts the following values:

  • normal: It is the default value, and it plays the animation in the forward direction as specified in the keyframes. After that, it restarts from the initial position. The animation starts from the beginning and finishes at the last keyframe.
  • reverse: The reverse animation plays backward from the end to the beginning. Then, it restarts from the end. Here, the animation begins with the last keyframe and then goes back to the first keyframe.
  • alternate: The animation plays in a forward direction from the beginning to the end. Then, it reverses from the end to the beginning. It creates a ping-pong like effect. It alternates between forward and reverse cycles.
  • alternate-reverse: The alternate-reverse is similar to the alternate property, but it starts by playing the animation backward from the end to the beginning.

Here’s an example of using the animation-direction property to create animations with different directions:

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

We have four boxes with different animation directions: normal, reverse, alternate, and alternatereverse. Each box uses a different animation direction by setting the animation-direction property accordingly.

animation-iteration-count

The animation-iteration-count property sets the number of times an animation should play. It accepts a numerical value to determine the iteration count. This property is useful for creating repetitive animations like loading animations etc.

Syntax:

  • infinite: Setting animation-iteration-count to infinite causes the animation to repeat infinitely, creating a continuous loop.
  • <number>: You can specify a particular number, such as 2, 3, or 5 to determine the exact count of animation repetitions.
  • initial: This initial value will set the iteration count to its default value.
  • inherit: The inherit value inherits the iteration count from the parent element.

Let’s take an example to visualize this property

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

In the above example, you can see that we have four boxes moving horizontally. The animation-iteration-count property controls how many times the animation iterates based on the value assigned to the iteration count property.

animation-fill-mode

The animation-fill-mode property specifies how an element should be styled before and after an animation is played. It determines whether or not the element retains the styles applied during CSS keyframes animation when the animation is not actively running.

Syntax:

The animation-fill-mode property can take the following values:

  • none: The element does not retain any styles from the animation before or after it runs. It is the default value.
  • forwards: The element retains the final keyframe styles after the animation completes. In other words, it sticks to the end state.
  • backwards: The element retains the styles from the first keyframe when the animation is not running (before it starts).
  • both: The element retains styles from both the first keyframe (before the animation starts) and the last keyframe (after the animation completes).

Here’s an example.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

In the above example, you can see how the animation-fill-mode property determines how an element should be styled both before and after the animation is executed.

Easing and Timing Functions of CSS Keyframes Animation

In the earlier section of the blog on CSS keyframes animation, we discussed a little bit about easing and timing functions. Let’s now take a deep dive into this.

Easing

Easing is like giving animations a natural touch. Think of it this way, when an object moves from point A to point B at a constant speed, it can seem a bit robotic, easing makes it smoother.

Without easing, it would move in a straight line, which often looks unnatural in user interfaces.

Easing functions provide a way to control the rate of change of an animation over its duration. These functions define the speed curve, determining how quickly or slowly an animation starts and ends.

Let’s take a look at some of the readily available easing functions in CSS:

linear

The linear timing function is the simplest and most straightforward of all timing functions. It creates a constant rate of change throughout the animation, meaning that the property being animated changes uniformly from the start value to the end value.

Linear Timing Function

The animation occurs at a constant speed, and there are no sudden accelerations or decelerations. The speed curve will be a straight line graph.

Speed Curve of Linear Timing Function

Speed Curve of Linear Timing Function

Let’s take an example and visualize the linear timing function.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

In this example, we have a linear animation where the circle moves in the positive X direction without any acceleration or deceleration.

ease-in

The ease-in timing function is one of the predefined timing functions available in CSS animations and transitions. It is a common choice when you want to create an animation that starts slowly and gradually accelerates as it progresses.

ease-in Timing Function

The shape of the speed curve resembles a smooth, concave curve that starts gently and then becomes steeper as it progresses.

Speed Curve of ease-in Timing Function

Speed Curve of ease-in Timing Function

Let’s take the previous example and update the timing function from linear to ease-in and see the difference.

linear fashion

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

As you can see the path or the line goes in a linear fashion, whereas the circle starts slowly and gradually increases its speed of propagation.

ease-out

The ease-out timing function is another predefined timing function available in CSS keyframes animation and transitions. Unlike ease-in, which starts slowly and accelerates, ease-out does the opposite. It begins with a faster animation speed and then gradually decelerates as it reaches its end.

ease-out Timing Function

The speed time graph here resembles a smooth curve that starts quickly and then gradually levels off, giving the impression of a gradual slowdown.

Speed Curve of ease-out Timing Function

Speed Curve of ease-out Timing Function

Let’s add the ease-out property to the previous example now.

ease-in-out

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

ease-in-out

The ease-in-out timing function is a commonly used predefined timing function in CSS keyframes animation and transitions.

ease-in-out Timing Function

As the name suggests, ease-in-out combines elements of both ease-in and ease-out, creating an animation that starts slowly, accelerates in the middle, and then decelerates as it approaches the end.

Speed Curve of ease-in-out Timing Function

Speed Curve of ease-in-out Timing Function

Let’s now update the previous example with an ease-in-out timing function.

ease-in-out

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

In this example, you can see that the animations start slow, speed up in the middle, and end slowly.

Let’s combine all the predefined timing functions in a single example and see how it looks.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

From the output above, you can see how the animation behaves differently with respect to various timing functions. By selecting the right timing function, you can achieve effects that range from smooth and gradual transitions to bouncy, elastic movements.

Timing

The steps() function allows you to create CSS keyframes animation with defined steps rather than smoothly transitioning between values. This function can create frame-by-frame animations and show the changes in the property being animated.

Syntax:

The value defines the number of intervals or steps the animation is divided into, and as an optional parameter, we can specify whether the steps start at the beginning (start) or end (end) of each interval.

Let’s now consider an example for demonstrating steps() function in animation by creating an animated clock movement.

animation durations

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

In this example, you can observe that the animation durations are set to correspond to the full rotation for hours, minutes, and seconds. The steps() function is used to create a discrete step animation.

However, you might be wondering how to create custom timing functions for CSS keyframes animation. You are not limited to the predefined timing functions mentioned above, you can also create timing functions depending on your specific needs.

Let’s explore that now.

cubic-bezier() function

To achieve a natural and realistic finish in CSS keyframes animation, relying solely on a constant speed animation may not be ideal. For example, consider an animation where an object is dropped to the floor: it should first accelerate downward and then rebound after making contact with the floor. This nuanced effect can be accomplished through the use of cubic bezier curves.

The cubic-bezier() timing function is a cubic Bézier curve defined by four control points, which influence the acceleration and deceleration of animation over time.

The cubic-bezier() function specifies the timing of CSS keyframes animation, allowing you to create custom motion curves beyond standard timing functions like ease, linear, ease-in, and ease-out.

Source

Syntax:

P0 and P3 represent the starting and ending points, respectively. They must be the coordinates (0, 0) and (1, 1). P1 and P2 are the control points, each with values between 0 and 1. P1 influences the curve’s initial acceleration. P2 influences the curve’s deceleration towards the end.

Let’s check out some simple animation timings created using the cubic-bezier() function.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

You can play around with the cubic-bezier() function to see the different curves that can be made.

The following are some of the most common timing functions you can use depending on your need for the CSS keyframes animation.

CSS keyframes

Source

Now that we’ve covered CSS keyframes animation basics and timing functions, let’s dive into specific properties that we can adjust to create better CSS keyframes animation.

Keyframes Animation Using CSS Transformations

CSS transformations are a set of properties and functions that allow you to manipulate the visual rendering of HTML elements. They provide a way to change how HTML elements look and behavior on the webpage.

With transformations, you can make web elements bigger or smaller, move them around, rotate them, or even make them look like they’re slanted, all without changing the actual content of your web page.

Combining transformation with CSS keyframes animation can bring a new creative visual experience to the web. You can also use them to create 3D effects that bring depth to your web designs.

Let’s look at each of the transform functions available in CSS:

translate()

The translate() function allows one to move an element from one position to another along either the horizontal (x) or vertical (y) axis. It allows you to change the element’s location on the web page without altering its size, rotation, or other visual properties.

Syntax:

The X value specifies the distance to move the element along the horizontal (x) axis. It can be a positive or negative value, indicating rightward or leftward movement, respectively. Similarly, the Y value specifies the distance to move the element along the vertical (y) axis.

vertical (y)

CSS Translation

You can use either pixel values or percentage values for X and Y, depending on your design requirements. You can also use translateX() and translateY() functions separately if you only want to move the element along one axis.

In this example, we will try to translate the car in X direction. You can be creative and add more life-like animations to the website.

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

You can also use percentage (%) values inside the translate property, and it is a really useful way. When a percentage value is used to translate an object, that percentage refers to the element’s own size, not the available space within the parent container.

scale()

The scale() function in CSS defines a transformation that allows you to resize an element on the 2D plane. This can be useful in scenarios where we need CSS keyframes animation like creating zoom-in effects, transitions, or responsive designs.

Scaling in X and Y direction

Scaling in X and Y direction

Syntax:

The X value specifies the horizontal scaling factor. Values that are less than 1 make the element narrower, while a value greater than 1 makes it wider. Similarly, Y value specifies the vertical scaling factor. The values are unitless.

Let’s take an example to see it in action.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

As you can see in the example, the image scales in response to the scale factor. This effect is often used in hover animations to provide users with a sense of interaction.

rotate()

The rotate() transformation function in CSS allows you to rotate elements, such as text or images, by a specified angle.

CSS Rotation

CSS Rotation

Syntax:

The angle here specifies the angle of rotation in degrees. Positive values rotate the element clockwise, and negative values rotate counterclockwise.

Here is an example.

HTML:

CSS:

See the Pen
Untitled
by adarsh (@adarsh-gupta101)
on CodePen.

skew()

The skew() function distorts an element by skewing it along the x-axis, y-axis, or both. Skewing creates a parallelogram-like effect.

 skew() function distorts an element

CSS Skew

Syntax:

You can either pass a single value so that both x and y take the same value or pass two values to specify x and y separately. You can also use the skewX() and skewY() functions to determine the skewing along specific axes.

Let’s take an example to see an example skew animation.

HTML:

CSS:

See the Pen
Credit cards
by adarsh (@adarsh-gupta101)
on CodePen.

As you can see in the above example, skewing can produce a tilting effect on an element. This is useful for showing depth perception or achieving real-world-like visual effects.

Now that you have good knowledge of CSS keyframes animation using transformation effects let’s build an entire landing page with several animations.

HTML:

CSS: