CSS Animation
What is Animation in CSS?
CSS animations assist you to create clean transitions and visual effects in your web pages without counting on JavaScript.
Basic Animation:
This example creates a simple sliding-in animation for a div detail.
@keyframes slideIn {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
div {
animation: slideIn 1s ease; /* Apply the slideIn animation to a div */
}
Animation with Delay and Repeat:
This instance creates a bouncing animation for a button that repeats infinitely with a 2 second duration.
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {
transform: translateY(0);
}
40% {
transform: translateY(-30px);
}
60% {
transform: translateY(-15px);
}
}
button {
animation: bounce 2s ease-in-out infinite; /* Apply a bouncing animation with a delay */
}
Animation with Opacity:
This instance creates a fade inside and outside animation for a paragraph with a 2-second duration.
@keyframes fadeInOut {
0%, 100% {
opacity: 0;
}
50% {
opacity: 1;
}
}
p {
animation: fadeInOut 2s linear infinite; /* Apply a fade in and out animation */
}
Animation on Hover:
This example rotates a div 360 degrees continuously whilst the person hovers over it.
@keyframes rotate {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
div:hover {
animation: rotate 2s linear infinite; /* Apply a rotation animation on hover */
}
Animation with Delay and Iteration Count:
This instance creates a coloration-converting animation for a div with a delay of one 2d and an generation count of one, making it play in reverse after attaining the end.
@keyframes colorChange {
0% {
background-color: #3498db;
}
50% {
background-color: #2ecc71;
}
100% {
background-color: #3498db;
}
}
div {
animation: colorChange 3s ease-in-out 1s infinite alternate; /* Apply a color-changing animation with delay and iteration count */
}
Animation with Keyframe Percentage:
@keyframes fadeIn {
25% {
opacity: 0.25;
}
50% {
opacity: 0.5;
}
75% {
opacity: 0.75;
}
100% {
opacity: 1;
}
}
span {
animation: fadeIn 2s linear infinite; /* Apply a fade-in animation with keyframe percentages */
}