Animation Basics
By utilizing CSS animations, you can make elements on the screen move and transform, adding a more dynamic feel to your page.
What are keyframes?
@keyframes
define how the animation should progress.
Similar to how a flipbook tells a story page by page, each page (keyframe)
defines how an element should change.
Start and End of Animations
CSS animations have a start and an end.
In the example below, 0%
is the start, and 100%
is the end.
CSS animations specify how the HTML element will change between these points.
@keyframes bounce {
0% {
transform: translateY(0); /* At 0%, apply translateY(0) */
}
50% {
transform: translateY(
-20px
); /* At 50%, apply translateY(-20px), move up 20px */
}
100% {
transform: translateY(
0
); /* At 100%, apply translateY(0), return to original position */
}
}
This code creates an animation called bounce
, making an HTML element move up and then back down.
Creating a Simple Animation
To apply an animation, you must specify what (animation-name
) and how long (animation-duration
) it should run.
div {
animation-name: bounce; /* Apply bounce animation */
animation-duration: 2s; /* Run animation for 2 seconds */
}
This makes the div
element execute the "bounce" animation for 2 seconds.
Adjusting Speed with animation-timing-function
You can control the speed of the animation using animation-timing-function
.
div {
animation-timing-function: ease-in-out;
}
ease-in-out
starts the animation slowly, speeds up in the middle, and ends slowly again.
Delaying Animation with animation-delay
Use animation-delay
to delay the start of an animation.
Example:
div {
animation-delay: 1s; /* Animation starts after 1 second */
}
Follow along by entering the highlighted code sections.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.