CSS Animations and Transitions
Introduction to CSS Animations
CSS animations allow you to create smooth transitions between different states of an element. They
provide an easy way to add movement and interactivity to web pages. Animations can be defined
using keyframes, which specify the styles at various points in the animation timeline.
Syntax of @keyframes
The @keyframes rule defines the animation. It specifies the styles for different points in the
animation:
@keyframes example {
0% { background-color: red; }
50% { background-color: yellow; }
100% { background-color: green; }
Applying Animations
To apply an animation to an element, use the following properties:
- animation-name: Specifies the name of the @keyframes animation.
- animation-duration: Defines how long the animation lasts.
- animation-timing-function: Sets the speed curve of the animation.
- animation-delay: Specifies a delay before the animation starts.
Example:
div {
animation-name: example;
animation-duration: 4s;
}
CSS Transitions
CSS transitions allow changes in CSS properties to occur smoothly over a duration. This is useful
for hover effects, buttons, and more.
To define a transition, use the 'transition' shorthand or individual properties:
- transition-property: Specifies the property to transition.
- transition-duration: Defines the duration of the transition.
- transition-timing-function: Sets the speed curve.
- transition-delay: Specifies a delay before the transition starts.
Example:
button {
transition: background-color 0.3s ease;
Differences Between Animations and Transitions
- Animations are more complex and can have multiple keyframes, whereas transitions only define a
start and end state.
- Animations can be looped or run indefinitely, while transitions are one-time changes.
- Animations require the @keyframes rule, while transitions can be applied directly.
Practical Examples
1. Button Hover Effect:
button:hover {
background-color: blue;
color: white;
transition: background-color 0.5s ease;
2. Spinning Animation:
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
div {
animation: spin 2s linear infinite;
Conclusion
CSS animations and transitions are powerful tools for creating dynamic and engaging web pages.
They improve user experience by adding interactivity and visual feedback.