Skip to main content
Practice

CSS Animation

Now, let's make the profile move up and down.

To move the profile up and down, we need to use the CSS animation property.


Using CSS Animation
selector {
animation: animationName duration;
}

Here, the selector specifies the element to which you want to apply the animation.

animationName refers to the name of the predefined animation, and duration represents the time the animation will play.

In CSS, animations are defined using the @keyframes keyword.

The @keyframes rule specifies each stage of the animation.

For example, the following code defines an animation named myAnimation.

Defining a CSS Animation
@keyframes myAnimation {
0% {
/* Initial stage style of the animation */
transform: translateY(0); /* At the start, apply translateY(0) */
}
50% {
/* Midpoint style of the animation */
transform: translateY(-20px); /* At 50%, apply translateY(-20px), moving up 20px */
}
100% {
/* Final stage style of the animation */
transform: translateY(0); /* At the end, apply translateY(0), returning to the original position */
}
}

To apply the myAnimation animation to an element with the class box and have it play for 2 seconds, you can write the CSS code as follows:

Applying the myAnimation CSS Animation
.box {
animation: myAnimation 2s;
}

Using the above code, an element with the class box will play the myAnimation animation for 2 seconds.

The CSS animation property is used to smoothly move or change elements. This allows you to add various dynamic effects to your webpage.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.