CSS **animations** allow you to create dynamic effects by gradually changing CSS properties over time using the @keyframes
rule.
1. Basic Syntax of CSS Animation
To animate an element, you define a **keyframes animation** and then apply it to an element.
@keyframes example { from { background-color: blue; } to { background-color: red; } } .box { width: 100px; height: 100px; background-color: blue; animation: example 2s linear infinite; }
2. Understanding @keyframes
The @keyframes
rule defines animation steps.
@keyframes fade { 0% { opacity: 0; } 100% { opacity: 1; } }
3. Applying Animation to an Element
Use the **animation** property:
.box { animation: fade 2s ease-in-out; }
4. Example: Bouncing Animation
@keyframes bounce { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-20px); } } .box { animation: bounce 1s ease-in-out infinite; }
5. Slide-in Animation
@keyframes slide-in { from { transform: translateX(-100%); } to { transform: translateX(0); } } .box { animation: slide-in 1s ease-out; }
6. Infinite Rotating Animation
@keyframes rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .box { animation: rotate 3s linear infinite; }
7. 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;
8. 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 **animations** make websites more interactive and engaging. Experiment with **keyframes, duration, timing functions, and iteration counts** to create stunning effects.