The @keyframes command

The @keyframes command sets keyframes (waypoints) for an animation. A keyframe represents various properties of our CSS element, such as position, size, color, etc., that are applied to the element at a specified time.

Syntax

css@keyframes animation name {
  keyframes
}

Example

Setting keyframes:

html<div id="elem"></div>
css@keyframes anim {
  from {
    margin-left: 0px;
  }
  to {
    margin-left: 400px;
  }
}

#elem {
  animation: anim 3s infinite;
  border: 1px solid black;
  width: 50px;
  height: 50px;
}

Результат:

Example

Now let's move our square using animation from top to bottom:

html<div id="elem"></div>
css@keyframes anim {
  from {
    margin-top: 0%;
  }
  to {
    margin-top: 10%;
  }
}

#elem {
  animation: anim 2s infinite;
  border: 1px solid black;
  width: 50px;
  height: 50px;
}

Результат:

Example

Let's increase the width of our shape using animation, setting key points in percentages:

html<div id="elem"></div>
css@keyframes anim {
  from {
    width: 10%;
  }
  to {
    width: 40%;
  }
}

#elem {
  animation: anim 2s infinite;
  border: 1px solid black;
  width: 50px;
  height: 50px;
}

Результат:

Example

Now let's change a transparency of our shape:

html<div id="elem"></div>
css@keyframes anim {
  from {
    background-color: #467CBC;
  }
  to {
    background-color: #C2DDFD;
  }
}

#elem {
  animation: anim 2s infinite;
  border: 1px solid black;
  width: 50px;
  height: 50px;
}

Результат:

See also