CSS propertyAnimations

@keyframes

Defines the stages of an animation, known as keyframes.

Initial value
not applicable (at-rule)
Inherited
No
Applies to
a rule in a stylesheet, used by animation-name
JavaScript
element.animate([{ opacity: 0 }, { opacity: 1 }], 500)
On this page

Example

#
CSS
@keyframes shake {
  0%, 100% { translate: 0; }
  20%, 60% { translate: -6px; }
  40%, 80% { translate: 6px; }
}

.input.error {
  animation: shake 0.4s;
}
Preview

Definition and usage

#

The @keyframes rule describes how an element should look at successive moments of an animation. You give it a name and then list the keyframes: from (0%) and to (100%), or any percentages in between.

The browser calculates the intermediate states between keyframes on its own. If you leave out from or to, it uses the element’s current styles as the missing keyframe, which lets you create animations “from the current state”.

You attach the rule to an element through animation-name or the animation shorthand. Keyframes can change many properties at once, but transform and opacity run the most smoothly.

Syntax

#
Syntax
@keyframes name {
  from { … }
  50% { … }
  to { … }
}

Values

#
  • from / to

    Two keyframes: the start and the end of the movement.
  • 0% / 50% / 100%

    percentages

    Three keyframes: halfway through, the element is in the upper right corner.
  • multiple properties

    Movement, a color change, and rotation at once.
  • no from

    from the current state

    No starting keyframe: the animation begins from the element’s normal styles.

Values in practice

#

from / to

Two keyframes: the start and the end of the movement.
@keyframes frames {
  from { transform: translateX(0); }
  to { transform: translateX(180px); }
}

0% / 50% / 100%

Three keyframes: halfway through, the element is in the upper right corner.
@keyframes frames {
  0%, 100% { transform: translate(0, 40px); }
  50% { transform: translate(180px, 0); }
}

multiple properties

Movement, a color change, and rotation at once.
@keyframes frames {
  50% { transform: translateX(180px) rotate(180deg); background: #f43f5e; border-radius: 50%; }
}

no from

No starting keyframe: the animation begins from the element’s normal styles.
@keyframes frames {
  to { transform: translateX(180px) scale(0.6); opacity: 0.4; }
}

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Name keyframes after the effect, for example fade-in, shake, slide-up. They are easy to reuse many times.
  • You can combine identical keyframes with a comma, e.g. 0%, 100% { … }, when the start and end look the same.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.