Animations and transitions in CSS allow you to create smooth, visually appealing changes in the appearance of elements without needing JavaScript. They can be used to change properties like colors, size, position, and more over a period of time.
Transitions enable you to change property values smoothly (over a given duration) when a certain event occurs (like a hover).
selector {
transition: property duration timing-function delay;
}
.button {
background-color: blue;
color: white;
padding: 10px 20px;
transition: background-color 0.5s ease;
}
.button:hover {
background-color: green;
}
In this example, when you hover over the button, the background color smoothly changes from blue to green in 0.5 seconds.
CSS Animations allow the animation of most HTML elements without using JavaScript or Flash. Animations are more complex than transitions and allow you to control the intermediate steps of an animation sequence.
@keyframes animationName {
from { property: value; }
to { property: value; }
}
selector {
animation-name: animationName;
animation-duration: time;
}
@keyframes slideIn {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
.box {
width: 100px;
height: 100px;
background-color: tomato;
animation-name: slideIn;
animation-duration: 2s;
}
Here, the .box
element will slide in from the left over a duration of 2 seconds.
infinite
).alternate
).
@keyframes bounce {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-50px);
}
}
.ball {
width: 50px;
height: 50px;
background-color: crimson;
border-radius: 50%;
animation: bounce 1s infinite;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.fade {
animation: fadeIn 2s ease-in forwards;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.spinner {
width: 50px;
height: 50px;
border: 5px solid lightgray;
border-top: 5px solid steelblue;
border-radius: 50%;
animation: spin 1s linear infinite;
}
Animations and transitions are powerful CSS features that can drastically enhance the user experience and visual appeal of your websites. By practicing and experimenting with timing, easing, and keyframes, you can bring your designs to life with smooth, dynamic motion!