CSS animations are a great way to add some life to your website. They can be used to create eye-catching effects, draw attention to important elements, and make your site more engaging for visitors. One of the most powerful tools for creating CSS animations is the @keyframes rule.
The @keyframes rule allows you to define a set of keyframes that describe how an element should be styled at different points during an animation. You can specify the starting and ending styles, as well as any intermediate styles that should be applied as the animation progresses.
Here's a basic example of how @keyframes works:
<style>
@keyframes example {
0% {background-color: red;}
50% {background-color: yellow;}
100% {background-color: green;}
}
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
</style>
<div></div>
In this example, we've defined a set of keyframes called "example" that will change the background color of a div element from red to yellow to green over a period of 4 seconds. We've then applied this animation to the div element using the animation-name and animation-duration properties.
Here's a breakdown of what's happening in the @keyframes rule:
When we apply this animation to the div element, it will smoothly transition from red to yellow to green over the course of 4 seconds.
Here's another example that uses @keyframes to create a bouncing ball animation:
<style>
@keyframes bounce {
0% {top: 0px;}
50% {top: 200px;}
100% {top: 0px;}
}
div {
position: relative;
width: 50px;
height: 50px;
background-color: blue;
animation-name: bounce;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
</style>
<div></div>
In this example, we've defined a set of keyframes called "bounce" that will move a div element up and down in a bouncing motion. We've then applied this animation to the div element using the animation-name, animation-duration, animation-iteration-count, and animation-timing-function properties.
Here's a breakdown of what's happening in the @keyframes rule:
When we apply this animation to the div element, it will bounce up and down in a smooth motion that repeats indefinitely.
The @keyframes rule is a powerful tool for creating CSS animations. By defining a set of keyframes that describe how an element should be styled at different points during an animation, you can create complex and engaging effects that will make your website stand out.