Introduction
CSS transitions and animations enhance user experience by adding smooth effects to elements. Transitions allow property changes over time, while animations provide more control over motion.
1. CSS Transitions
Transitions enable smooth changes between CSS states.
Syntax:
selector {
transition: property duration timing-function delay;
}
CSSExample:
.button {
background-color: blue;
transition: background-color 0.5s ease-in-out;
}
.button:hover {
background-color: red;
}
CSSThis smoothly changes the background color when hovered.
Common Transition Properties:
ease
(default) – Starts slow, speeds up, then slows downlinear
– Moves at a constant speedease-in
– Starts slow, then acceleratesease-out
– Starts fast, then slows downease-in-out
– Starts slow, speeds up, then slows down
2. CSS Animations
Animations provide more control over movement using @keyframes
.
Syntax:
@keyframes animation-name {
from { property: value; }
to { property: value; }
}
selector {
animation: name duration timing-function delay iteration-count direction;
}
CSSExample:
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.box {
animation: fadeIn 2s ease-in;
}
CSSThis fades in the .box
element over 2 seconds.
Animation Properties:
infinite
– Runs continuouslyforwards
– Retains final state after animationalternate
– Reverses direction every cycle
3. Combining Transitions and Animations
Transitions and animations can be combined for advanced effects.
Example:
@keyframes slideUp {
from { transform: translateY(100px); }
to { transform: translateY(0); }
}
.button {
transition: background-color 0.3s;
animation: slideUp 1s ease-in;
}
.button:hover {
background-color: green;
}
CSSConclusion
CSS transitions and animations create engaging visual effects, improving interactivity and user experience.