CSS animations allow you to create dynamic effects by gradually changing CSS properties over time using the @keyframes
rule.
1. What is @keyframes
?
The @keyframes
rule defines an animation sequence by specifying key points along the animation timeline.
2. Basic Syntax of @keyframes
To animate an element, you define a **keyframes animation** and apply it using the **animation** property.
@keyframes example { from { background-color: blue; } to { background-color: red; } } .box { width: 100px; height: 100px; background-color: blue; animation: example 2s linear infinite; }
3. Understanding Keyframe Steps
You can define multiple steps using percentages.
@keyframes fade { 0% { opacity: 0; } 50% { opacity: 0.5; } 100% { opacity: 1; } }
4. Applying Animation to an Element
.box { animation: fade 2s ease-in-out infinite; }
5. Example: Bouncing Animation
@keyframes bounce { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-20px); } } .box { animation: bounce 1s ease-in-out infinite; }
6. Slide-in Animation
@keyframes slide-in { from { transform: translateX(-100%); } to { transform: translateX(0); } } .box { animation: slide-in 1s ease-out; }
7. Infinite Rotating Animation
@keyframes rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .box { animation: rotate 3s linear infinite; }
8. Customizing Animation
You can specify:
- Duration:
animation-duration: 2s;
- Timing Function:
animation-timing-function: ease-in-out;
- Delay:
animation-delay: 1s;
- Iteration Count:
animation-iteration-count: infinite;
- Direction:
animation-direction: alternate;
9. Combining Multiple Animations
@keyframes grow { 0% { transform: scale(1); } 100% { transform: scale(1.5); } } @keyframes colorChange { 0% { background-color: red; } 100% { background-color: blue; } } .box { animation: grow 2s ease-in-out infinite, colorChange 3s linear infinite; }
Conclusion
CSS keyframes make websites more interactive and engaging. Experiment with keyframes, duration, timing functions, and iteration counts to create stunning effects.