The Ultimate Guide to CSS Keyframes Animation

Adarsh M

Posted On: April 22, 2024

view count125392 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:

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

In the above example, you can see that multiple CSS keyframes animation catch the user’s attention. For instance, the mouse wheel animation can lead the user to scroll down to see the rest of the content.

 CSS keyframes animation catch the user's attention

Mouse Scroll Animation

On mobile view, the navigation bar turns into a hamburger icon with a smooth reveal animation, providing a seamless user experience without sudden changes on the website.

Let’s now learn how to create some advanced CSS keyframes animation using motion paths.

CSS Keyframes Animation Using Motion Path

In the earlier section of this blog on CSS keyframes animation, you saw how to translate objects in a straight line. This is useful for simple animations, like hover effects. However, there are scenarios where we might want to move objects along a specific trajectory or path. That’s when we can use the CSS motion path.

CSS Keyframes Animation Using Motion Path

Custom Paths

The CSS motion path feature allows you to animate any web element along a specified path, giving you more control over the motion and animation of elements on a webpage. It enables elements to move along a predefined path.

In the following example, the circle is moving through a predefined path.

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

To understand the CSS motion path, let’s start with the basics.

The motion-path or offset-path property specifies the exact path through which an element should move. It accepts various values, such as geometric shapes (circles, ellipses, or polygons) or path data defined using SVG commands.

 path() function

The path we want to translate can be defined using the path() function. Alternatively, you can use the predefined geometric shapes, such as circle(), ellipse(), polygon(), and inset() property.

Let’s take an example and see how it moves through different paths, such as circular, triangular, etc.

HTML:

CSS:

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

As you can see in the example, you can combine offset-path with other animation properties to create dynamic effects. The offset-path property sets the path for an element’s motion, while offset-distance controls the position along the path. You can use percentages to precisely position the element.

One drawback of using CSS motion path is that a few browsers still don’t have support for this property, which can lead to a negative experience for some users. While modern browsers have good support, it may not work in older versions as expected. Therefore, it’s important to consider fallback options.

CSS motion path

Source

Keyframes Animation Using CSS Sprites

One of the underrated ways to create clean keyframes animation is using CSS sprites. Sprite animation is a powerful technique used to create smooth and efficient animations on the web by combining several images into a single sprite sheet and then using CSS to display specific frames of the sprite.

The idea behind CSS sprite animation is that by using CSS, specific frames can be displayed at different times, creating the illusion of motion.

Let’s recreate the Twitter retweet button and its animation using a CSS sprite as an example. The following is the sprite image, our goal is to move through each part one by one.

Sprite of Retweet Button

Sprite of Retweet Button

HTML:

CSS:

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

In the above example, you can see that we can create sprite animations where a series of images or frames are combined into a single sprite sheet. These frames represent different stages of an animation or different states of an object.

CSS Variables for Dynamic Animations

CSS variables allow you to create dynamic and customizable animations. These variables allow you to change animation properties on the fly, enabling you to create interactive animations. CSS variables are declared using the — prefix, and they can be declared at various levels, from global (document-wide) to scoped (within specific elements or selectors).

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

HTML:

CSS:

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

You can see that we are using JavaScript to send the mouse position, and in the CSS, we are taking the value via the CSS variable. This opens up a way for various other animations that can be built using CSS variables.

 CSS variable custom properties

Source

However, while working with CSS variables, some browsers and older versions of some browsers don’t have support for CSS variables. This may lead to unexpected behavior, so consider implementing fallback options.

Maximizing Performance for CSS Animations and Keyframes

Animations play a vital role in the user interface and user experience. But they are a double-edged sword. Unnecessary or resource-heavy animations can harm user experience, so optimizing all animations for better performance is important.

Modern browsers are good at animating two CSS properties: transform and opacity. For all other properties, achieving a consistently smooth 60 Frames Per Second (FPS) can be more challenging.

Smooth web animations typically aim for a 60 Frames Per Second (FPS) rate. If each frame takes more than about 16.7 milliseconds (1000ms divided by 60 ≈ 16.7), users will notice a delay in the animation.

One way to improve CSS performance is by using CSS Hardware Acceleration. Although CSS animations, transforms, and transitions are not GPU accelerated by default, specific CSS properties force the browser to use hardware acceleration instead of executing it on slower software rendering engines.

3D animations always use hardware acceleration, so even if you are not using any kind of 3D animations or transformations, you can still use hardware acceleration to improve the overall performance of the animation. You can use properties like:

The above properties essentially do nothing, but the remaining part of the animations will be accelerated by hardware, which can improve the performance in desktop and mobile browsers.

Minimize Layout and Paint Operations

An efficient web performance is a top priority without that, all your heavy CSS keyframes animation are simply not worth it. One key aspect of achieving this goal is minimizing layout and paint operations while rendering web pages.

According to Chrome developers, to display some elements on a webpage, the browser follows a series of steps:

  1. Style: The browser calculates the styles that apply to each element on the page. This includes determining properties like fonts, colors, and positioning.
  2. Layout: After computing styles, the browser proceeds to generate the layout. This involves determining the size, position, and geometry of each element. It creates a blueprint for how elements will be arranged on the page.
  3. Painting: Once the layout is established, the browser paints the pixels onto separate layers. This process includes filling in the content of each element with the appropriate colors and images.
  4. Composite Rendering: Finally, the browser composites or combines these layers and draws the resulting composition to the screen. This step results in the visual representation of the webpage that users see and interact with.

Layout (reflow) and paint (repaint) operations can be resource-intensive and slow down your web page. So when you use properties like left:10px, it will trigger the browser to reflow, which can be a performance-intensive task.

Red Flag:

Green Flag:

Using CSS transform properties can minimize layout changes and have better performance during animations. In the same way, instead of directly updating the values of width, height, top, left, right properties of an element, using transforms can result in better performance.

You can also optimize browser performance with will-change property. This property hints to the browser which properties will change and need optimization. This can improve performance by allowing the browser to prepare for the animation.

Although will-change can enhance the performance by reducing the impact of layout changes and repaints, you have to use it only on properties that are expected to change, to avoid unnecessary overhead.

Making Your CSS Keyframes Animation Accessible

As we already know, most websites these days have some kind of CSS keyframes animation, but it is crucial to ensure that these CSS keyframes animation don’t affect the user experience of people who need special support.

Some users with vestibular motion disorders will have a hard time interpreting some animations. But if they have turned off animation effects on their device, the media feature prefers-reduce-motion query that will be triggered, and they can have less animation.

Windows Settings for Accessibility

Windows Settings for Accessibility

The animation will display as expected on the webpage for normal users. However, if you’ve chosen to disable animation effects on your device, the following code will detect and remove the applied animations on the element:

This will improve the accessibility and overall user experience for those who can’t tolerate or interpret CSS keyframes animation.

Debugging CSS Keyframes Animation

The browser developer tools significantly help debugging CSS keyframes animation. Chrome Developer Tools has a number of features that can help you diagnose and resolve CSS keyframes animation issues.

You can do this by opening the Developer Tools panel. Now, navigate to the Animations tab in the Developer Tools panel.

Animations Tab

Animations Tab

The Animations tab in Chrome Developer Tools serves a dual purpose. First, it enables you to inspect animations closely. You can slow down the animation, replay it, and examine its source code, providing valuable insights into its behavior.

Additionally, the Animations tab allows you to modify CSS keyframes animation. This means you can make adjustments to the timing, delay, duration, or keyframe offsets of an animation group, providing you with control over its execution.

Let’s take the following example and see how to use the Animations tab. Here we have two animations, one for changing the color and another for increasing the width of an element

Once you open the Animations tab, hover over its thumbnail in the Overview pane to view a preview of it.

  Snapshot of Animations Tab

Snapshot of Animations Tab

With the Animations tab, you can slow down animations, replay them frame by frame, and even delve into the source code behind the animation groups.

You can also see the styles and animation properties by clicking on it, which will take you to the styles box of the developer tool.

Chrome Developer Tools

Chrome Developer Tools

By clicking on the ease symbol, you will get a modal where you can alter the timing functions, just like shown in the output below:

alter the timing functions

You can select the timing function, which is predefined, or you can even play around to find the best cubic-bezier curve that fits your animation.

   Example of a cubic-bezier Curve

Example of a cubic-bezier Curve

You can even change the keyframe rules and use them to find the best value for the property.

Color Picker From Chrome Developer Tools

Color Picker From Chrome Developer Tools

The Chrome Developer Tools also allows you to analyze the performance of an animation. The Performance tab provides a timeline of events, including script execution, rendering, and painting.

Chrome Developer Tools

Look for spikes or prolonged periods in the timeline, which may indicate performance bottlenecks during CSS keyframes animation.

Testing the Responsiveness of CSS Keyframes Animation

Once you’ve come up with the design for your CSS keyframes animation, you need to test it to ensure that it provides the same user experience across the web.

You can test the responsiveness of your websites and web apps that use CSS keyframes animation on different viewports with LT Browser, which allows you to select multiple device viewports simultaneously and run tests on your web applications.

Testing the Responsiveness of CSS Keyframes Animation

One notable feature is the ability to perform mobile website testing on multiple device viewports simultaneously, reducing the need to manually resize the browser window.

Testing the Responsiveness of CSS Keyframes Animation

DOWNLOAD LT BROWSER Download LT Browser

Here is a quick rundown of the LT Browser:

CSS Keyframes Animation Best Practices

CSS keyframes animation gives life to a website, but having too much can be a problem as it will make the user uncomfortable while using the web app.

Here are some key best practices for CSS keyframes animation:

  • Minimize Animations for User Experience: Having multiple CSS keyframes animation can make it difficult for the user to decide where to focus. Ensure your animations serve a purpose, such as guiding user attention or providing feedback.
  • Animations should serve to enhance the user experience, not just for the sake of aesthetics. Consider the specific goals of your CSS keyframes animation, whether a simple hover button or a sliding animation that reveals subcategories, creating a logical and smooth flow of information.

  • Use GPU-Accelerated Properties: As mentioned earlier, specific CSS properties, such as transform and opacity, are hardware-accelerated by the GPU. Utilizing these properties in CSS keyframes animation is more efficient and leads to smoother transitions, especially on modern devices.
  • Browser Compatibility: Different browsers may interpret CSS keyframes animation slightly differently. Thoroughly test your animations across various browsers to ensure they work as expected. Although vendor prefixes are less common today, they may still be necessary for older browsers.
  • Use the transform Property: The transform property is hardware-accelerated on modern browsers, making it highly efficient. Utilize it for CSS keyframes animation involving translation, rotation, scaling, and skewing.
  • Combine multiple transformations into a single transform rule whenever possible. This reduces the number of reflows and repaints, leading to smoother animations.

  • Avoid Animating Layout Properties: Layout properties, such as width, height, margin, and padding, are responsible for determining the position and size of elements on the page. Animating these properties can trigger layout recalculations, leading to reflows, which are computationally expensive and can significantly slow down your web page.
  • Avoid Animating Root Elements: It is recommended to avoid animating root elements, which is another important best practice for CSS keyframes animation. The root elements typically include <html> and <body> tags and should remain static. Making the whole page animated would hardly provide good value to your UX.

Wrapping Up

CSS keyframes animation bring life and interactivity to web elements, enhancing the overall user experience and adding a touch of dynamism to web design. With some creativity, they can turn your vision into a digital masterpiece.

In this blog, we have covered almost everything about CSS keyframes animation that you need to know to create an engaging web experience.

From understanding key concepts like @keyframes and animation properties to exploring advanced techniques like timing functions and sprite animations, you are now ready to start building the web experience that your end user expects.

Frequently Asked Questions (FAQs)

What are CSS keyframes?

CSS keyframes define the exact styles an element will have at specific points in the animation sequence, like at the beginning, middle, or end. This lets you create smooth transitions and complex animations with just CSS.

What is a 0 to 100 keyframe?

In CSS animations, 0% and 100% are special keyframes representing the beginning and end of the animation, respectively. They define the starting and ending styles of the animation. In between these points, you can add additional keyframes to create smooth transitions or define changes throughout the animation.

Author Profile Author Profile Author Profile

Author’s Profile

Adarsh M

Adarsh is a full-stack JavaScript developer based out of India. He loves creating meaningful technical content on Twitter, where he connects with like-minded individuals and developer communities. He shares his knowledge on Twitter through insightful threads!

Blogs: 12



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free