Comprehensive Guide to CSS Keyframes: Top 7 Use Cases and Properties
Sep 05, 2024 8 Min Read 2770 Views
(Last Updated)
CSS Keyframes are a powerful tool for adding dynamism and motion to your website. This guide will delve into the intricacies of CSS Keyframes and how to effectively use them to create engaging and interactive web pages.
They have the power to bring your website to life, but they can also be a bit tricky to master. In this comprehensive guide, we’ll dive deep into the world of CSS Keyframes and show you how to use them to create dynamic, engaging animations.
Table of contents
- Introduction to CSS Keyframes
- The Syntax of CSS Keyframes
- The Different CSS Keyframes and Properties
- 1) Timing Functions in CSS Keyframes
- 2) Creating Looped Animations
- 3) Multi-step Animations and CSS Keyframes
- 4) The Power of Alternating Animations
- 5) Understanding Shorthand Values
- 6) Exploring Fill Modes
- 7) Dynamic Animations with CSS Variables
- Concluding Thoughts...
- FAQs
- What are CSS keyframes?
- What is the keyframe percentage?
- How do you add a keyframe?
- How do I see all keyframes?
Introduction to CSS Keyframes
CSS Keyframes are a powerful tool in CSS that allows us to create animations. The @keyframes rule, a core component of CSS animations, is used to define these stages, which are represented as percentages of the total animation duration.
However, they can often be misunderstood due to their unique characteristics. In this guide, we’ll demystify CSS Keyframes, showing how they can be used to create impressive animations.
If you’re already advanced with CSS, you may still find some cool and obscure nuggets of information near the end of this guide.
Must Read | Complete CSS Tutorial: Essential Guide to Understand CSS [2024]
The Syntax of CSS Keyframes
At the heart of CSS Keyframes is the idea of interpolating between chunks of CSS. Let’s consider a simple example where we define a Keyframe animation to smoothly move an element’s horizontal position from -100%
to 0%
:
@keyframes slide-in {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0%);
}
}
The @keyframes
statement requires a name, in this case, slide-in
. This name works like a global variable. We can apply this animation to specific selectors using the animation
property.
Also Explore: Types of CSS: A Comprehensive Guide to Styling Web Pages
The Different CSS Keyframes and Properties
Let us now look at a few use cases and understand different CSS Keyframes and their properties and how exactly they work:
1) Timing Functions in CSS Keyframes
CSS Keyframes have a built-in library of timing functions. The default value is ease
, but this can be overridden with the animation-timing-function
property.
Timing functions control the acceleration and deceleration of an animation, giving it a more natural or dynamic feel. Let’s create a simple example using HTML and CSS to demonstrate timing functions in CSS keyframes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Keyframes with Timing Functions</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
animation: move 3s infinite alternate;
}
@keyframes move {
0% {
left: 0;
}
100% {
left: calc(100% - 100px);
}
}
/* Timing function examples */
.linear {
animation-timing-function: linear;
}
.ease {
animation-timing-function: ease;
}
.ease-in-out {
animation-timing-function: ease-in-out;
}
.ease-in {
animation-timing-function: ease-in;
}
.ease-out {
animation-timing-function: ease-out;
}
</style>
</head>
<body>
<div class="box linear"></div>
<div class="box ease"></div>
<div class="box ease-in-out"></div>
<div class="box ease-in"></div>
<div class="box ease-out"></div>
</body>
</html>
- In this example, we have a
.box
class that represents a blue square div element. This square will be animated to move horizontally across the screen. - We define a keyframe animation named
move
. This animation moves the box from the left side of the screen to the right side. - The animation will take 3 seconds to complete (
animation: move 3s infinite alternate;
) and will repeat infinitely (infinite
) in an alternating direction (alternate
). - We also have five additional classes
.linear
,.ease
,.ease-in-out
,.ease-in
, and.ease-out
that apply different timing functions to the animation. - The
.linear
class applies a linear timing function, which means the animation progresses at a constant speed throughout its duration. - The
.ease
,.ease-in-out
,.ease-in
, and.ease-out
classes apply easing timing functions. Easing functions change the rate of the animation’s progress over time, resulting in smoother motion. Each of these classes applies a different type of easing effect (ease-in, ease-out, ease-in-out, etc.).
When you run this HTML code in a browser, you’ll see five blue squares moving horizontally across the screen. Each square will have a different animation timing function applied to it, demonstrating the visual differences between linear and various easing functions.
Also Read: A Complete Guide to HTML and CSS for Beginners
2) Creating Looped Animations
By default, Keyframe animations run only once. However, we can control this using the animation-iteration-count
property. A special value that comes in handy is infinite
, it can be used to create a never-ending animation like a loading spinner.
Here’s a simple example of a looped animation using CSS keyframes with the animation-iteration-count
property set to infinite
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Looped Animation Example</title>
<style>
/* Define keyframes for the animation */
@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-20px); }
100% { transform: translateY(0); }
}
/* Apply animation to an element */
.box {
width: 100px;
height: 100px;
background-color: red;
animation: bounce 1s ease-in-out infinite;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
In this example:
- We define a keyframe animation named
bounce
using@keyframes
. This animation will make an element bounce up and down. - The
bounce
animation starts with the element’s original position (0%
), moves it upward by20px
(50%
), and then returns it to the original position (100%
). - We apply the
bounce
animation to an element with the class.box
. - The animation has a duration of
1s
(1 second), uses easing (ease-in-out
) for smooth acceleration and deceleration, and repeats infinitely (infinite
) with theanimation-iteration-count
property.
As a result, when you open this HTML file in a web browser, you’ll see a red box bouncing up and down continuously. This animation loops indefinitely due to the infinite
value specified for the animation-iteration-count
property.
This example demonstrates how to create a simple looped animation using CSS keyframes and apply it to an HTML element. You can adjust the keyframes and animation properties to create different types of animations based on your requirements.
Must Read: A Comprehensive Guide to HTML and CSS Roadmap [2024]
3) Multi-step Animations and CSS Keyframes
CSS Keyframes allow us to add more than just two steps to our animation. We can do this through the use of percentages. This allows us to break our animation into multiple distinct steps, each with its timing function.
Let’s go through a simple example of a multi-step animation using CSS keyframes. We’ll animate the color of a box through multiple steps. Here’s how it looks with HTML and CSS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multi-step Animation Example</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
animation: colorChange 5s infinite; /* Applying the animation */
}
@keyframes colorChange {
0% {
background-color: red; /* Start color */
}
50% {
background-color: blue; /* Middle color */
}
100% {
background-color: green; /* End color */
}
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
In this example:
- We define a
<div>
element with the class box, which represents the box we want to animate. - In the CSS, we set the initial size and background color of the box.
- We define a keyframe animation named
colorChange
using@keyframes
. This animation gradually changes the background color of the box over some time. - Inside the
@keyframes
rule, we specify the percentages of the animation’s duration (0%, 50%, and 100%) and the corresponding styles at each percentage. - At
0%
, the background color of the box is set to red (the starting color). - At
50%
, the background color of the box is set to blue (the middle color). - At
100%
, the background color of the box is set to green (the end color). - Finally, we apply the
colorChange
animation to the.box
element with a duration of5s
and set it to run infinitely usinginfinite
.
When you run this code, you’ll see the box smoothly transitioning its background color from red to blue to green, then repeating the animation infinitely.
This example demonstrates the use of multi-step animations in CSS keyframes, where you can define various intermediate states of animation by specifying percentages of its duration.
Also Read: Best Techniques for Creating Seamless Animations with CSS and JavaScript [2024]
4) The Power of Alternating Animations
One intriguing feature of CSS Keyframes is the ability to alternate animations. For example, if we want an element to “breathe”, we could set up a 3-step animation, but a more elegant approach is to use the animation-direction
property.
CSS animations with the animation-direction
property allows elements to alternate between two or more keyframe animations, creating a back-and-forth motion effect. Let’s go through a simple example to demonstrate this concept:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alternating CSS Animations</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: blue;
animation: move-right 2s linear infinite alternate; /* Using alternate animation-direction */
}
@keyframes move-right {
0% { transform: translateX(0); }
100% { transform: translateX(200px); }
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
In this example:
- We define a blue square
.box
with dimensions of 100px by 100px. - The
@keyframes
rule defines the animation namedmove-right
, which translates the box horizontally from 0 to 200 pixels. - In the
.box
class, we set the animation property tomove-right
, specifying 2 seconds, a linear timing function, and an infinite iteration count. - Additionally, we include the
alternate
value for theanimation-direction
property, which makes the animation alternate direction on each cycle.
Here’s what’s happening:
- Initially, the box starts at its original position.
- When the animation runs, it moves the box horizontally to the right by 200 pixels over 2 seconds.
- When it reaches the end of the animation, it reverses direction and moves the box back to its original position.
- This back-and-forth motion continues indefinitely due to the
infinite
iteration count.
The animation-direction
property provides options to control how animations play, including reversing the animation direction.
By using the alternate
value, we achieve a seamless back-and-forth animation effect. This technique is useful for creating dynamic and visually appealing UI elements on web pages.
Also Read: 10 Best HTML and CSS Project Ideas for Beginners
5) Understanding Shorthand Values
We’ve covered many properties related to animations, and fortunately, like timing
, we can use the animation
shorthand to combine these properties.
The animation
shorthand property in CSS is used to specify multiple animation-related properties in a single declaration.
Let’s look at an example to demonstrate the usage of animation shorthand property along with CSS keyframes:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Animation Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="box"></div>
</body>
</html>
CSS:
.box {
width: 100px;
height: 100px;
background-color: #3498db;
animation: moveBox 2s ease-in-out infinite alternate;
}
@keyframes moveBox {
0% {
transform: translateX
Let’s understand this:
- In the HTML file, we have a simple
div
element with a class of “box”. This is the element that we will animate. - In the CSS file, we define the initial styles for the “.box” class, specifying its width, height, and background color.
- The
animation
shorthand property is used to specify the animation for the “.box” element. It consists of the following components:moveBox
: This is the name of the animation, which corresponds to the keyframes defined later in the CSS.2s
: This is the duration of the animation, set to 2 seconds.ease-in-out
: This is the timing function for the animation, which defines how the animation progresses over time. In this case, it starts slow, speeds up, and then slows down again.infinite
: This specifies that the animation should repeat indefinitely.alternate
: This specifies that the animation should alternate direction on each iteration.
- The
@keyframes
rule defines the animation itself. In this case, we’re defining the “moveBox” animation, which moves the box horizontally across the screen. - Inside the
@keyframes moveBox
rule, we define two keyframes:- At
0%
, the box starts at its initial position (no horizontal translation). - At
100%
, the box is translated 200 pixels to the right using thetransform
property.
- At
When you view this HTML file in a web browser, you’ll see a box moving horizontally across the screen smoothly, continuously, and alternately changing direction at the end of each iteration. This animation is achieved using the animation
shorthand property along with CSS keyframes.
Must Read: Mastering CSS Selectors: A Comprehensive Guide
6) Exploring Fill Modes
One of the more confusing aspects of Keyframe animations is fill modes. When an animation ends, it’s as if the CSS in the to
block doesn’t exist anymore.
To solve this, we use the animation-fill-mode
property with the value forwards
. This allows us to persist the final value from the animation. Here’s an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Animation Fill Mode Example</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
animation-name: move;
animation-duration: 2s;
animation-fill-mode: forwards; /* Animation fill mode */
}
@keyframes move {
from {
transform: translateX(0);
}
to {
transform: translateX(200px);
}
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
Here’s what happened:
- We’ve created a red-colored box (represented by the
<div>
element with the class.box
) using CSS. - We’ve defined a CSS animation called
move
using@keyframes
. This animation moves the box horizontally from its initial position to 200 pixels to the right. - The
animation-fill-mode: forwards;
property is applied to the.box
class. This property specifies how the element should be styled before and after the animation.- With
animation-fill-mode: forwards;
, the element retains the styles of the last keyframe after the animation completes. In this case, after the animation moves the box 200 pixels to the right, the box will stay in that position (translateX(200px)
) even after the animation ends.
- With
So, when you view this HTML document in a browser, you will see a red box moving horizontally to the right and staying in that position after the animation completes, thanks to the animation-fill-mode: forwards;
property.
Also Explore: Debugging CSS: Everything You Should Know [2024]
7) Dynamic Animations with CSS Variables
When CSS Keyframes are combined with CSS variables, they become even more powerful. For example, we can create a bouncing-ball animation, and use CSS variables to control the bounce height.
This allows us to create reusable, customizable Keyframe animations. Let’s understand through an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bouncing Ball Animation</title>
<style>
:root {
--bounce-height: 100px; /* Initial bounce height */
}
@keyframes bounce {
0%, 100% {
transform: translateY(0); /* Start and end position */
}
50% {
transform: translateY(-var(--bounce-height)); /* Peak of the bounce */
}
}
.ball {
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%; /* Make it a circle */
animation: bounce 1s infinite; /* Apply the bounce animation */
}
</style>
</head>
<body>
<label for="bounce-height-range">Bounce Height:</label>
<input id="bounce-height-range" type="range" min="50" max="200" value="100">
<div class="ball"></div>
<script>
// JavaScript to update CSS variable value based on input range
const bounceHeightRange = document.getElementById('bounce-height-range');
const ball = document.querySelector('.ball');
bounceHeightRange.addEventListener('input', () => {
document.documentElement.style.setProperty('--bounce-height', `${bounceHeightRange.value}px`);
});
</script>
</body>
</html>
What happened here:
- We use CSS variables to define the bounce height (
--bounce-height
) in the:root
pseudo-class. This allows us to easily change the bounce height dynamically. - We define a keyframe animation called
bounce
. This animation moves the ball up and down using thetransform: translateY()
property. At the 50% mark of the animation, the ball reaches its peak bounce height. - The
.ball
class styles the appearance of the ball. It’s a red circle (border-radius: 50%
) with a width and height of 50px. - We apply the
bounce
animation to the ball using theanimation
property. The animation runs infinitely (infinite
) and lasts for 1 second (1s
). - We include an
<input>
element with a range type to control the bounce height dynamically. When the range input value changes, it updates the--bounce-height
CSS variable value accordingly using JavaScript.
This example demonstrates how to create a bouncing-ball animation using CSS keyframes and CSS variables. The use of CSS variables allows for dynamic control over animation properties, providing flexibility and interactivity in web animations.
Understand more: Style Matters: Exploring Essential CSS Properties You Must Know
Concluding Thoughts…
CSS has evolved significantly over the past few years, becoming an expressive, flexible, and powerful language. Understanding CSS Keyframes allows us to create dynamic, engaging animations, making our websites more interactive and enjoyable.
CSS Keyframes can seem intimidating at first, but with knowledge and practice, they can become an invaluable tool in your web development toolkit.
Also Read: Top 20 HTML & CSS Interview Questions With Answers
FAQs
What are CSS keyframes?
CSS keyframes are used in animations to define specific stages of the animation sequence. They specify the styles at various points during the animation’s duration.
What is the keyframe percentage?
The keyframe percentage indicates the point in the animation’s duration where a specific style is applied. It ranges from 0% to 100%.
How do you add a keyframe?
Keyframes are added using the @keyframes
rule in CSS. Within this rule, you specify the percentage of the animation duration and the styles to be applied at each stage.
How do I see all keyframes?
You can view all keyframes defined in your CSS stylesheet by inspecting the stylesheet directly in your browser’s developer tools.
Did you enjoy this article?