CSS Animations
CSS Animations allow you to create dynamic effects by transitioning between different styles over time. They are defined using @keyframes
and controlled with properties like animation-name
, animation-duration
, and more.
Key Topics
Basic Animation
A basic animation transitions an element's property values using the @keyframes
rule.
<style>
@keyframes colorChange {
0% {
background-color: #007BFF;
}
100% {
background-color: #FF5733;
}
}
.basic-animation {
width: 100px;
height: 100px;
animation: colorChange 2s ease;
}
</style>
<div class="basic-animation"></div>
Explanation: The background color of the element changes from blue to orange over 2 seconds using the colorChange
animation.
Timing Functions
Timing functions control the speed of the animation at different points during its execution. Common values include ease
, linear
, ease-in
, and ease-out
.
<style>
@keyframes moveRight {
0% {
transform: translateX(0);
}
100% {
transform: translateX(100px);
}
}
.timing-animation {
width: 100px;
height: 100px;
background-color: #007BFF;
animation: moveRight 3s ease-in-out;
}
</style>
<div class="timing-animation"></div>
Explanation: The element smoothly moves 100px to the right over 3 seconds, accelerating and decelerating with ease-in-out
.
Infinite Animation
The animation-iteration-count
property lets you repeat an animation a specific number of times or infinitely.
<style>
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.5);
}
}
.infinite-animation {
width: 100px;
height: 100px;
background-color: #FF5733;
animation: pulse 2s infinite;
}
</style>
<div class="infinite-animation"></div>
Explanation: The element pulses continuously by scaling between its original size and 1.5 times larger.
Multiple Keyframes
Animations can include multiple keyframes to define intermediate states, creating more complex effects.
<style>
@keyframes multiStep {
0% {
background-color: #007BFF;
transform: translateX(0);
}
50% {
background-color: #FF5733;
transform: translateX(50px);
}
100% {
background-color: #28A745;
transform: translateX(100px);
}
}
.multi-keyframe-animation {
width: 100px;
height: 100px;
animation: multiStep 4s ease;
}
</style>
<div class="multi-keyframe-animation"></div>
Explanation: The element changes its background color and moves across the screen in multiple steps defined by the keyframes.
Key Takeaways
- Basic Animation: Use
@keyframes
to define animations andanimation
properties to apply them. - Timing Functions: Control the speed progression of animations with values like
ease-in-out
. - Infinite Animation: Repeat animations indefinitely using
animation-iteration-count: infinite
. - Multiple Keyframes: Create complex animations by defining multiple intermediate states.
- Control: Customize animations with properties like
animation-delay
andanimation-direction
.