CSS Transitions and Animations
CSS Transitions and Animations bring life and interactivity to your web
pages by allowing you to smoothly change property values over time. They
enhance user experience by providing visual feedback and engaging effects
without the need for JavaScript.
CSS Transitions
Transitions let you change CSS property values
gradually, rather than instantly, when a state changes — like when a user
hovers over a button.
Key Properties:
·
transition-property
—
Which CSS properties will animate (e.g., background-color
, width
).
·
transition-duration
—
How long the transition lasts (e.g., 0.3s
).
·
transition-timing-function
— The speed curve of the transition (e.g., ease
, linear
, ease-in-out
).
·
transition-delay
—
Delay before the transition starts.
Example:
button {
background-color: blue;
transition: background-color
0.3s ease;
}
button:hover {
background-color: green;
}
When the user hovers over the button, its
background color smoothly changes from blue to green over 0.3 seconds.
CSS Animations
Animations allow more complex sequences of
property changes, defined by keyframes that specify styles at various points in
the animation timeline.
Key Properties:
·
@keyframes
— Defines
the stages of the animation.
·
animation-name
—
Specifies the name of the keyframes to apply.
·
animation-duration
—
How long one cycle of the animation lasts.
·
animation-iteration-count
— How many times the animation runs (infinite
for endless).
·
animation-timing-function
— The speed curve of the animation.
·
animation-delay
—
Time before the animation starts.
·
animation-fill-mode
— Controls how styles apply before and after animation.
Example:
@keyframes slideIn {
from {
transform:
translateX(-
100%);
opacity:
0;
}
to {
transform:
translateX(
0);
opacity:
1;
}
}
.box {
animation-name: slideIn;
animation-duration:
1s;
animation-timing-function: ease-out;
}
This animation slides the .box
element in from the left while fading it in.
Tips for Using Transitions and Animations
·
Use subtle animations to
improve UX without overwhelming users.
·
Combine animations with
JavaScript for interactive effects.
·
Be mindful of
performance—avoid animating expensive properties like box-shadow
or width
too often.
·
Use will-change
sparingly to optimize rendering for animated elements.