MakeW3web

Animation basics

Animations allow you to create visual effects that add movement and interactivity to your designs. Here's a simple explanation of animation basics, including keyframes, timing, and easing, along with some examples:

Keyframes

Keyframes define the intermediate states of an animation, allowing you to specify how an element should change over time. To create a keyframe animation in CSS, you use the `@keyframes` rule followed by a name for your animation and a series of CSS rules that define the intermediate states of the animation. For example:

@keyframes slide {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(100px);
  }
}

div {
  animation: slide 1s ease-in-out infinite alternate;
}

This creates an animation called `slide` that moves a `div` element horizontally by 100 pixels. The `0%` keyframe specifies the starting state of the animation (in this case, no translation), while the `100%` keyframe specifies the ending state of the animation (in this case, a translation of 100 pixels).

Timing

Timing refers to the duration and repetition of an animation. In CSS, you can control the timing of an animation using the `animation-duration`, `animation-delay`, `animation-iteration-count`, and `animation-direction` properties. For example:

div {
  animation: slide 1s ease-in-out infinite alternate;
  animation-delay: 1s;
  animation-iteration-count: 3;
  animation-direction: alternate-reverse;
}

This animates the `div` element with the `slide` animation, but adds a delay of 1 second before the animation begins, limits the animation to 3 iterations, and reverses the direction of the animation on alternate iterations.

Easing

Easing refers to the way an animation accelerates and decelerates over time. You can use the `animation-timing-function` property to control the easing of an animation. There are several predefined easing functions, such as `ease-in`, `ease-out`, `ease-in-out`, and `linear`, or you can define your own custom easing function using the `cubic-bezier()` function. For example:

div {
  animation: slide 1s cubic-bezier(0.25, 0.1, 0.25, 1) infinite alternate;
}

This animates the `div` element with the `slide` animation, but uses a custom easing function that creates a slow start, fast middle, and slow end to the animation.

By using keyframes, timing, and easing in your animations, you can create dynamic and engaging designs in CSS. With these basic concepts and techniques, you can create a wide variety of animations that enhance the user experience of your web pages.

Was this page helpful?