What is Animation in CSS: Simple Explanation and Examples
animation lets you change the style of an element smoothly over time without needing JavaScript. It works by defining keyframes that describe the start and end states, and the browser fills in the steps between to create motion or effects.How It Works
Think of CSS animation like a flipbook or a movie. You create a few important frames called keyframes that show the start and end of a change, such as moving a box from left to right or changing its color. The browser then draws all the in-between frames automatically, making the change look smooth and natural.
This happens by defining rules inside @keyframes and then applying those rules to an element with the animation property. You can control how long the animation lasts, how many times it repeats, and if it should pause or reverse.
Animations in CSS run directly in the browser, so they are fast and don’t need extra code like JavaScript. This makes it easy to add simple motion effects that improve user experience and make websites feel more lively.
Example
This example moves a square from left to right and changes its color smoothly over 3 seconds, then repeats forever.
html, body {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
}
.box {
width: 100px;
height: 100px;
background-color: #3498db;
animation: slideAndColor 3s infinite alternate;
}
@keyframes slideAndColor {
0% {
transform: translateX(0);
background-color: #3498db;
}
100% {
transform: translateX(200px);
background-color: #e74c3c;
}
}When to Use
Use CSS animations when you want to add smooth, eye-catching effects to your website without slowing it down. They are great for:
- Drawing attention to buttons or links by making them gently move or change color.
- Creating loading spinners or progress indicators.
- Animating page elements on scroll or hover to improve user interaction.
- Making transitions between states feel natural, like sliding menus or fading images.
Because CSS animations run in the browser, they are best for simple or medium complexity effects. For very complex animations or interactive games, JavaScript might be better.
Key Points
- CSS animations use
@keyframesto define the animation steps. - The
animationproperty controls timing, repetition, and direction. - Animations run smoothly in the browser without extra code.
- They improve user experience by adding motion and feedback.
- Best for simple to moderate effects, not complex interactive animations.