Sobes.tech
Junior

Для чего нужны keyframes и как они работают?

sobes.tech AI

Answer from AI

@keyframes — a CSS rule that defines the keyframes of an animation. It allows creating a sequence of states for an element at different times, which the browser will smoothly transition between, creating a motion effect. It works by defining a set of styles for the element at specific percentages of time (from 0% to 100%) or using the keywords from (0%) and to (100%).

To use keyframes, you need to:

  1. Define a @keyframes rule with a unique name.
  2. Inside @keyframes, specify styles for different time marks (percentages or from/to).
  3. Apply the created animation to an element using the CSS property animation.
@keyframes slidein {
  from {
    transform: translateX(0%); // Starting state: no X translation
  }

  to {
    transform: translateX(100%); // Ending state: translated 100% along X
  }
}

.element {
  animation-name: slidein; // Name of the animation defined above
  animation-duration: 3s; // Duration of the animation
  animation-timing-function: ease-in-out; // Speed function of the animation
  animation-delay: 1s; // Delay before the animation starts
  animation-iteration-count: infinite; // Number of times the animation repeats (here infinite)
  animation-direction: alternate; // Direction of the animation (forward, then reverse)
}

Main properties of animation, used together with @keyframes:

Property Description
animation-name Name of the @keyframes to apply.
animation-duration Duration of one animation cycle (e.g., 2s, 500ms).
animation-timing-function Speed function of the animation (e.g., linear, ease, ease-in, cubic-bezier).
animation-delay Delay before the animation starts (e.g., 1s).
animation-iteration-count Number of times the animation repeats (infinite for endless repetition).
animation-direction Direction of the animation (normal, reverse, alternate, alternate-reverse).
animation-fill-mode Determines which styles are applied to the element before and after the animation.
animation-play-state Determines whether the animation is running or paused.