CSS animations allow developers to add motion effects to web elements declaratively, without relying on JavaScript. By defining styles in CSS, animations become lightweight, easy to maintain, and highly performant.
To create motion effects in CSS, three core concepts are used: transitions, transforms, and animations. Here’s a quick breakdown:
- CSS Transitions enable smooth changes between two visual states of an element, triggered by events such as hovering or clicking. For example, you might change the background color of a button when it’s hovering.
- CSS Transforms manipulate the appearance of an element by modifying its size, shape, or position, without affecting other elements on the page. Examples include rotating, scaling, or translating elements.
- CSS Animations define a sequence of visual changes to an element over time. Unlike transitions, animations can have multiple keyframes, allowing for complex and continuous effects such as spinning or pulsing.
In this blog, we’ll focus on CSS animations and explore their implementation, properties, and advanced techniques to create engaging and dynamic web designs. Let’s dive in!
CSS 2D Transforms
CSS provides two types of transformations: 2D and 3D. 2D transforms work in a flat, two-dimensional space and are easier to implement. They let you manipulate elements in various ways using the following functions:
- scale(): Changes the size of an element. You can make it larger or smaller along the X and Y axes. For example, scale(2) doubles the size, while scale(0.5) halves it.
- translate(): Moves an element horizontally, vertically, or both without affecting its surrounding elements. It uses pixel or percentage values, e.g., translate(50px, 20px).
- rotate(): Rotates an element around a fixed point (its center by default). The rotation is specified in degrees or turns, e.g., rotate(45deg) for a 45-degree rotation.
- skew(): Distorts an element along the X or Y axis, creating a sloped effect. For instance, skew(20deg, 10deg) skews the element by 20 degrees along the X-axis and 10 degrees along the Y-axis.
- matrix(): Combines multiple transformations (scale, translate, rotate, and skew) into a single function. It offers fine-grained control over transformations but requires six numerical values, e.g., matrix(1, 0, 0, 1, 50, 50).
Keynote:
Transforms occur outside of the document flow, meaning they don’t change the layout or position of other elements on the page. Only the transformed element and its children are affected.
These transformations are commonly used for animations, interactive designs, and effects that enhance user interfaces.
Here is the code to get a basic idea about the 2D transformation:
<div class="parent">
<p>Hover any of the below boxes!</p>
<div class="transform">
<div class="box scale">Scale</div>
<div class="box translate">Translate</div>
<div class="box rotate">Rotate</div>
<div class="box skew">Skew</div>
<div class="box matrix">Matrix</div>
</div>
</div>
.transform {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.box {
background: #ff5757;
color: white;
text-align: center;
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 8px;
transition: all 0.5s ease;
cursor: pointer;
}
.scale:hover {
transform: scale(1.5);
}
.translate:hover {
transform: translate(20px, -20px);
}
.rotate:hover {
transform: rotate(90deg);
}
.skew:hover {
transform: skew(-20deg, 20deg);
}
.matrix:hover {
transform: matrix(1.5, 0, -0.5, 1.5, 30, -20);
}
CSS 3D Transforms
CSS 3D Transforms enable you to manipulate elements in three-dimensional space, adding depth and creating realistic, interactive effects on web pages. Unlike 2D transforms, which only operate on a flat plane, 3D transforms let you move elements closer or farther from the viewer, creating a sense of depth.
The Z-Axis
The Z-axis introduces depth by allowing movement forward (toward the viewer) or backward (away from the viewer). While:
- The X-axis controls horizontal movement (left and right),
- The Y-axis controls vertical movement (up and down),
- The Z-axis determines how far or near an element appears in 3D space.
Perspective
Perspective acts like a camera lens, controlling how you view 3D transformations. The perspective value determines the intensity of the 3D effect:
- A smaller value (e.g: 30px) makes elements appear more dramatic and exaggerated.
- A larger value (e.g: 600px) creates a subtler, flatter appearance with less depth.
The following example lets you experiment with perspective values to see how they affect 3D transforms.
<div class="container">
<div class="box rotateX">Rotate X</div>
<div class="box rotateY">Rotate Y</div>
</div>
.container {
display: flex;
gap: 60px;
}
.box {width: 100px;
height: 100px;
background: #ff5757;
color: white;
display: flex;
justify-content: center;
align-items: center;
transition: transform 0.5s ease;
cursor: pointer;
}
.rotateX:hover {
transform: perspective(300px) rotateX(70deg);
}
.rotateY:hover {
transform: perspective(300px) rotateY(60deg);
}
2D vs. 3D Transforms
- 2D Transforms: Elements move or rotate along a flat surface, like a piece of paper. For instance, you can move an element left, right, up, or down.
- 3D Transforms: Elements can tilt, rotate, or move along the Z-axis (closer to or farther from the viewer), adding a new dimension to your designs. This resembles objects viewed in a real-world 3D space.
Let’s Animate with CSS
CSS animations function similarly to the animations you might create in video editing software like Camtasia or Final Cut Pro, where you use keyframes to define specific moments in an animation. In CSS, keyframes serve as the blueprint for creating smooth and dynamic visual transitions.
When you create a CSS animation, you define different keyframes, each representing a specific point or moment in the animation sequence. These keyframes describe how the styles of an element should change at various points in time, and together, they create the illusion of motion.
A Real-World Analogy: The Bouncing Ball
Imagine a ball bouncing. At the highest point in the air, the ball pauses for a split second — this is one keyframe. As the ball descends halfway to the ground, it hits another keyframe. Finally, when it hits the floor, it reaches yet another keyframe. These distinct stages (the air, the mid-fall, and the ground) define the movement of the animation.
By combining these keyframes, you can produce a seamless bouncing animation. The graph below visually represents the ball’s movement across various keyframes, helping you understand how CSS animations work in action:
In the above graph, Let’s assume the animation begins at the 20% mark, where the ball’s height is at its peak of 100px. This point represents the starting keyframe of the animation. As the animation progresses to 40%, the ball begins descending, reducing its height to around 50px. Similarly, the ball continues its journey, hitting various heights at different keyframes. These distinct points — the starting height, mid-points, and ending height — collectively define the animation sequence.
And guess what? These keyframes are what bring the animation to life!
Let’s Create an Animation!
Are you excited to see how we can bring this concept to life with code? Let’s dive in and create the animation step by step. By the end, you’ll have a smooth bouncing-ball effect, as you see in the output below.
To create any CSS animation, there are two key components:
- Defining keyframes using the @keyframes at-rule.
- Applying the animation using the animation property and specifying its values.
1.Defining Keyframes
The first step in creating an animation is defining the keyframes using the @keyframes at-rule. Keyframes specify the styles an element should have at specific points during the animation.
Here’s an example of keyframes for a bouncing ball:
@keyframes bouncing-ball {
25% {
transform: translate(80px, 200px);
background: green;
}
50% {
transform: translate(100px, 0);
background: yellow;
}
100% {
transform: translate(250px, 200px);
background: red;
}
}
In this example, I named the animation “bouncing-ball”, where the keyframes define specific transformations and style changes at different points in the animation timeline. These keyframes create smooth transitions between states, resulting in a continuous multi-step animation.
For instance:
- At 25%, the ball moves diagonally down and changes its color to green.
- At 50%, it reaches the top of its bounce, with its color changing to yellow.
- At 100%, it moves farther to the right and back down, turning red.
Once this keyframe rule is defined, you can reuse the animation multiple times throughout your project by simply referencing it in your CSS.
You can define keyframes at any percentage you need, such as 10%, 20%, 30%, and so on, up to 100%. However, CSS also provides an alternate shorthand using the from and to keywords:
- from is equivalent to 0% (the starting state).
- to is equivalent to 100% (the ending state).
Let’s see an example with the from and to keywords, used to create a smooth calling effect
@keyframes calling {
from {
transform: scale(0);
}
to {
transform: scale(2);
opacity: 0;
}
}
In this example:
- from starts the element at a scale(0) (completely shrunken).
- to scale it to scale(2) (twice its size) while reducing its opacity to 0 (fading out).
These keyframes ensure a smooth transition from the starting state (from) to the final state (to).
2.Applying the animation
Now we’ve created our keyframes, the next step is to apply them to an element using the animation property. CSS animations consist of several sub-properties, which you can define individually or combine into a shorthand. Let’s break this down step by step.
Individual Animation Properties
Below is a list of all the animation-related properties and their functions:
-
animation-name: Specifies the name of the keyframes declaration to use.
-
animation-duration: Defines how long the animation takes to complete one cycle (e.g., 5s or 500ms).
-
animation-timing-function: Controls the pacing of the animation between keyframes (e.g., linear, ease-in, ease-out).
-
animation-delay: Specifies the delay before the animation starts.
-
animation-iteration-count: Determines how many times the animation should repeat (e.g., 1, infinite).
-
animation-direction: Specifies whether the animation should alternate direction (normal, reverse, alternate, alternate-reverse).
-
animation-fill-mode: Defines how styles are applied before and after the animation (e.g., none, forwards, backwards, both).
-
animation-play-state: Allows the animation to be paused or running (running, paused).
Animation – A Shorthand
Instead of defining each property individually, CSS allows you to combine them into a single shorthand property:
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
You don’t need to include every property in the shorthand; omit the ones you don’t want to set, and the browser will apply their default values.
Let’s apply this to our bouncing ball animation:
.ball {
animation: bouncing-ball 5s linear infinite;
}
In this example:
-
animation-name: Specifies the name of the keyframes (bouncing-ball).
-
animation-duration: The animation takes 5 seconds to complete one cycle.
-
animation-timing-function: The animation progresses linearly.
-
animation-iteration-count: The animation runs infinitely.
You can also combine multiple animations by separating them with commas. For example:
.ball {
animation: bounce 5s linear infinite, color-change 3s ease-in-out infinite;
}
That’s it! Your animation is now functional and beautifully smooth. The shorthand syntax simplifies your code and makes it easier to manage.
Want to try it yourself? You can experiment with this animation on (Bouncing-ball, Calling-effect) Codepen and tweak the properties to see how they affect the behavior.
Animation Chaining in CSS
Animation chaining in CSS refers to creating a sequence of animations where one starts immediately after another finishes. This can be achieved using the animation-delay property to schedule when each animation begins, creating a smooth transition from one effect to the next.
@keyframes bounce {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-50px);
}
100% {
transform: translateY(0);
}
}
@keyframes changeColor {0% {
background-color: red;
}
100% {
background-color: blue;
}
}
.element {
animation: bounce 2s ease-in-out, changeColor 2s ease-in-out 2s;
}
In this example, the bounce animation lasts for 2 seconds, while the changeColor animation starts 2 seconds after the bounce begins, thanks to the 2s delay. The animations are chained in sequence, where the changeColor effect begins once the bounce animation is completed.
Properties that can be Animate
In CSS, not all properties can be animated. Only those properties that can change an element’s appearance smoothly over time are animatable. Examples include properties related to size, position, color, and transparency.
For instance, you can animate properties like:
- Opacity: Animating opacity creates fade-in or fade-out effects.
- Transform: Properties like transform allow you to rotate, scale, skew, or move elements.
- Color: Properties such as color, background-color, and border-color.
- Box-Model: Properties like width, height, margin, and padding can be animated.
- Positions: Properties like top, left, right, and bottom can be animated, but it’s better to use transform for performance reasons.
- Text Effects: Animatable properties include font-size, letter-spacing, and line-height.
These properties are animatable because they allow for gradual changes that look natural. On the other hand, some properties, like display, cannot be animated because they change instantly (they snap from one state to another). Such properties don’t support smooth transitions, which makes animations impossible for them.
Performance Considerations
To make animations smooth and efficient, it’s essential to optimize how the browser processes them. Poorly optimized animations can lead to laggy performance, making your site feel slow and unresponsive. Here’s how you can avoid this:
Use the Right Properties
- Best Options: Animate properties like transform and opacity. These are lightweight and handled efficiently by the browser using GPU acceleration during the composition phase, avoiding layout recalculations.
- Avoid Heavy Properties: Avoid animating properties like width, height, margin, or top. These force the browser to recalculate styles, reflow the layout, and repaint the screen, which slows down performance.
Keep Animations Smooth
For smooth animations, the browser needs to render at 60 frames per second (FPS). This means it has only 16.7 milliseconds to complete all tasks required for one frame.
How the Browser Processes Animations
In those 16.7 milliseconds, the browser performs these steps:
- Recalculate Styles: When a property changes, the browser recalculates the styles.
- Recalculate Layout: The browser determines new positions and sizes for elements (also called reflow).
- Repaint: The browser updates the visible appearance of the elements on the screen.
- Compose Layers: Finally, the browser combines layers and renders the final frame.
If these steps take longer than 16.7 milliseconds, the browser skips frames, leading to jank (choppy animations).
Key Tips for Smooth CSS Animations
- Animate Lightweight Properties: transform (e.g., move, scale, rotate) and opacity (e.g., fading effects). These are GPU-optimized and skip layout recalculations.
- Avoid Expensive Properties: width, height, margin, top, or left: These trigger style recalculations, layout changes, and repaints, which are costly for performance.
Browser Compatibility and Fallbacks
CSS animations may not behave consistently across all browsers, so ensuring compatibility is essential for a smooth user experience.
Older browsers might not fully support certain animation features, so it’s important to test your animations using tools like Can I Use to check which CSS properties work across different platforms.
When animations are not supported, you can provide fallbacks – such as static styles or simpler transitions – so the user still gets a functional design.
Additionally, use vendor prefixes like -webkit- for browsers like Safari or older versions of Chrome to maximize support.
For example, animations might require prefixed keyframes to ensure proper rendering. Testing animations and providing fallbacks guarantees a consistent and reliable experience for all users, regardless of their browser.
Summary
CSS animations are a powerful tool for adding visual appeal and interactivity to web pages. By understanding and optimizing key animation properties like transform and opacity, you can create smooth and efficient animations that enhance user experience without compromising performance. It’s also important to test browser compatibility and provide fallbacks to ensure animations work reliably across different browsers. Tools like CanIUse can help you verify which CSS features are supported.
In addition to basic animations, Advanced CSS Animation Techniques allow you to take your skills to the next level. For instance, using the cubic-bezier function gives you precise control over the animation timing, allowing you to create custom easing effects beyond the standard options like ease, linear, or ease-in-out. Techniques such as chained animations, animation delays, and layering multiple animations with commas (animation: bounce 2s ease, fade 1s linear) can add depth and creativity to your designs.
By combining smooth animations, advanced techniques, and ensuring cross-browser compatibility, you can create dynamic and engaging web experiences that feel modern and polished.
Also, if you are looking for a JavaScript or React job, please search for them on Talent500.
Add comment