Unleashing the Power of CSS Animations with the @keyframes Rule: A Beginner's Guide
CSS animations are a powerful tool for bringing website designs to life, and the @keyframes rule is the key to creating dynamic and engaging animations. In this article, you'll learn the basics of CSS animations and the @keyframes rule, and also learn how to create simple animations that will add visual interest and interactivity to your website.
First, you'll be introduced to the @keyframes rule in detail, including its definition and syntax. You’ll also learn about the various properties that can be used to control animations, such as the animation-duration and animation-iteration-count properties.
Next, I'll show you how to use the @keyframe rule to create both basic and more creative animations. Examples and code snippets that you can use as a starting point for your own animations will be provided.
Finally, this article offers best practices and guidelines for utilizing keyframes in animation creation. By following these recommendations, you can optimize the performance of your website and ensure that your animations are compatible across various browsers and devices.
Let's get started!
The @keyframes rule
@keyframes at-rule is used to declare blocks of code that should be executed at any specified moment during the animation. It specifies the precise times at which the current style will gradually give way to the new style and enables this change to be gradually incorporated into the element.
Basic Syntax
@keyframes animation-name {
keyframe-selector {
property: value;
}
}
The animation-name is a unique name given to the animation and is used to apply the animation to an element.
The keyframe-selector is used to specify at which point during the animation the properties within the keyframe should be applied. This can be a percentage (e.g. 0%, 50%, 100%) or the keywords from and to (equivalent to 0% and 100% respectively).
For example, to create a basic animation that changes the background color of an element from red to blue:
@keyframes change-color {
from {
background-color: red;
}
to {
background-color: blue;
}
}
Once the keyframes are defined, they can be applied to an element using the animation property.
#example-element {
animation-name: change-color;
animation-duration: 5s;
}
Using animation sub-properties, keyframe animations provide more control over the animation, giving the developer the ability to specify the animation steps and timing. This makes it possible to create more complex and sophisticated animations, such as those that involve multiple elements or dynamic changes in an element's properties over time. Examples of these animation sub-properties are:
The animation-duration property is used to specify the length of time that the animation should take to complete. The value is specified in seconds (s) or milliseconds (ms).
The animation-iteration-count property is used to specify the number of times that the animation should be played. The default value is 1, and the animation will only play once. A value of infinite will cause the animation to loop indefinitely.
The animation-timing-function is used to specify the speed curve of the animation, which allows you to control the speed of the animation as it progresses. The property can be set to a number of pre-defined values such as
ease
,linear
,ease-in
,ease-out
, andease-in-out
, or you can use thecubic-bezier
function to define a custom timing curve. The default value isease
.The animation-delay is used to specify a delay before the animation starts.
The animation-direction is used to specify whether the animation should play forward, backward, or alternate between the two.
The animation-play-state is used to specify whether the animation is running or paused.
The animation-fill-mode is used to specify how the element should be styled when the animation is not in motion (before it starts, after it ends, or both).
You can use the shorthand animation property to set several sub-properties at once:
animation: animation-name animation-duration animation-timing-function animation-iteration-count animation-direction animation-fill-mode animation-play-state animation-delay;
Real-World Keyframe Animation Examples
A Loading Spinner Animation:
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .loading-spinner { animation: spin 1s linear infinite; }
In this example, the loading-spinner class will rotate 360 degrees continuously with a linear timing function and a duration of 1 second.
A Fade-In Animation:
@keyframes fadeIn { from { opacity: 0; color: red; } to { opacity: 1; color: yellow; } } .fade-in-element { animation: fadeIn 2s ease-in-out; opacity: 0; }
In this example, the fade-in-element class will change its opacity from 0 to 1 and also change text colours in 2 seconds with an ease-in-out timing function.
CSS keyframe animations allow for more complex and detailed animations, as they allow for multiple keyframes to be defined and timed, rather than a simple transition between two states. Take a look at the example below:
A bouncing ball animation:
@keyframes bounce { 0% { transform: translateY(0); } 50% { transform: translateY(-30px); } 100% { transform: translateY(0); } } .ball { animation: bounce 1s ease-in-out infinite; }
In this example, a ball class element will move up and down continuously as if it is bouncing, with a duration of 1 second, and an ease-in-out timing function.
A Sliding Carousel Animation:
@keyframes slideCarousel { 0% { transform: translateX(0%); } 25% { transform: translateX(-100%); background-color: indianred;} 50% { transform: translateX(-200%); background-color: grey; } 75% { transform: translateX(-300%); background-color: red;} 100% { transform: translateX(-400%); } } .carousel-item { animation: slideCarousel 2s linear infinite; }
In this example, the carousel-item class elements will slide horizontally from left to right continuously while changing to different background colors, with a duration of 2 seconds and a linear timing function.
A Text Typing Animation:
@keyframes typeText { 0% { width: 0; } 1% { width: 0; } 99% { width: 100%; } 100% { width: 100%; } } .typing-text { animation: typeText 3s ease-in-out infinite; overflow: hidden; white-space: nowrap; }
In this example, the text inside the typing-text class element will appear as if it is being typed out, with a duration of 3 seconds and an ease-in-out timing function.
A Weather Animation:
@keyframes moveClouds { 0% { transform: translateX(0); } 100% { transform: translateX(-30%); } } /* Keyframe animation for the raindrop falling */ @keyframes fall { 0% { transform: translateY(0); } 100% { transform: translateY(300px); } } .cloud { width: 180px; height: 100px; background: #ccc; border-radius: 100px; animation: moveClouds 10s linear infinite; } /* Define the raindrop shape and animation */ .rain { width: 10px; height: 20px; background: #dde; position: absolute; border-radius: 50%; animation: fall 1s ease-in-out infinite; } /* Add multiple raindrops to create the illusion of rain falling */ .cloud:after, .cloud:before { content: ""; position: absolute; top: 50%; width: 10px; height: 20px; background: #dde; border-radius: 50%; animation: fall 1s ease-in-out infinite; } /* stagger animation-delay for each raindrop */ .cloud:after { left: 40%; animation-delay: 0.1s; } .cloud:before { right: 80%; animation-delay: 0.2s; }
In this example, the cloud class element will move horizontally from left to right continuously, simulating the clouds moving across the sky. The rain class element, and the :before and :after cloud elements will move vertically from top to bottom continuously, simulating rain falling.
3D Transformation:
@keyframes transform { 0% { transform: rotateX(0deg) rotateY(0deg) translateZ(0px) scale(1); } 50% { transform: rotateX(180deg) rotateY(180deg) translateZ(200px) scale(2); background-color: #324d; } 100% { transform: rotateX(360deg) rotateY(360deg) translateZ(0px) scale(1); background-color: #333e; } } /* Apply animation to object */ .content { width: 100px; height: 100px; background-color: #344e; animation: transform 5s ease-in-out infinite; }
3D transformations can be used to create an animation of an object rotating in 3D space.
These are just a few examples of complex keyframe animations that can be used in real-world scenarios. These examples require other CSS styles and HTML structure to work properly, which are all written in the JSFiddle links.
Best Practices to follow when using CSS Keyframes
To ensure that your animations are efficient, performant, and visually pleasing, it's important to follow best practices when using keyframes. By doing so, you can create animations that work seamlessly across different browsers and devices, making your website more engaging and enjoyable for users.
Here are some best practices to follow when using CSS keyframes:
Keep it simple: When creating keyframe animations, it's best to start with simple animations and build complexity as needed. This will make it easier to debug and optimize the animation.
Reuse keyframes: Reusing keyframes across multiple animations can help reduce the amount of code you need to write and make it easier to maintain.
Use percentage keyframe-selectors: Instead of using specific keyframe-selectors (from and to), use percentages to define the stages of the animation. This makes it easier to adjust the animation and ensures that ithe animations work consistently across different browsers.
Optimize performance: Keep in mind that animations can be resource-intensive, so it's important to optimize the animation for performance. This means reducing the number of elements, avoiding unnecessary calculations, and using efficient animation techniques.
Test on different devices: It's important to test your animations on different devices, including different screen sizes and resolutions, to ensure they look and perform as expected.
Don't overuse animations: While animations can be a great way to add visual interest to your website, overusing them can be overwhelming for users. Use them sparingly and make sure they add value to the user experience.
Be consistent: Consistency is important when it comes to animations, so make sure your animations have the same duration, easing and delay, this will make the animation look more polished and professional.
Conclusion
In conclusion, the @keyframes rule is a powerful tool for creating animations on the web, giving developers the ability to create captivating and dynamic animations that can elevate the user experience and make a website truly stand out. This article has provided an overview of the basics of the @keyframes rule and highlighted some best practices to follow when using it. It's important to remember that as with any skill, practice is key to mastering the use of CSS keyframes and understanding the concepts and use-cases. By putting in the time and effort to understand and master the @keyframes rule, web developers can take their website's design to new heights and create truly mesmerizing animations that will keep users engaged and coming back for more.
Subscribe to my newsletter
Read articles from Kenebebh Banigo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Kenebebh Banigo
Kenebebh Banigo
Frontend developer and Technical writer