This tutorial aims to enlighten you on the best practices when creating animations using Cascading Style Sheets (CSS). CSS animations make web pages more interactive and engaging, but it’s important to use them effectively to avoid unnecessary performance problems and to maintain a good user experience.
CSS animations are created by transitioning between various CSS configurations over a period of time. CSS allows elements to change values over a specified duration, animating the property changes, rather than having them occur immediately.
In CSS, @keyframes
rule is used to create animations. Keyframes hold what styles the element will have at certain times. For example:
@keyframes example {
0% {background-color: red;}
50% {background-color: yellow;}
100% {background-color: green;}
}
Use Transform and Opacity Properties for Animations: They are the most performant properties to animate because they can be handled by the compositor thread with the help of the GPU.
Avoid Animating Layout Properties: Animating properties like width, margin, padding, etc. can trigger layout changes, paint, and composite stages, which are less performant.
Use will-change
Property with Caution: The will-change
property is used to inform the browser that an element will have its style changed. However, misuse of will-change
can cause performance issues.
Use requestAnimationFrame
for JavaScript-Based Animations: If you need to use JavaScript for your animations, make use of the requestAnimationFrame
method. It provides a smoother and more efficient animation by syncing with the computer's display refresh rate.
@keyframes slidein {
from { margin-left: 100%; width: 300%; }
to { margin-left: 0%; width: 100%; }
}
This @keyframes
animation slides an element into view from the right edge of the screen.
@keyframes fadein {
from { opacity: 0; transform: scale(0.5); }
to { opacity: 1; transform: scale(1); }
}
This animation fades an element in, while also scaling it up from 50% to 100%.
In this tutorial, we've covered the basics of CSS animations, how to use keyframes, and some best practices to keep in mind. Remember that while animations can greatly improve your site's user experience, they can also harm performance if not used judiciously.
Exercise 1: Create a CSS animation that changes the color of a square div over 5 seconds.
Exercise 2: Create a CSS animation that moves a circle div from the left side of the screen to the right over 3 seconds.
@keyframes colorchange {
0% {background: red;}
50% {background: green;}
100% {background: blue;}
}
.square {
animation: colorchange 5s infinite;
}
This animation will continuously change the background color of the .square
div from red to green to blue over 5 seconds.
@keyframes moveright {
0% {transform: translateX(0);}
100% {transform: translateX(100%);}
}
.circle {
animation: moveright 3s infinite;
}
This animation will move the .circle
div from the left edge of its container to the right edge over 3 seconds.