CSS Animation for the Rails developer

Dec 08, 2014

Animations are made in CSS with the @keyframes directive. You’ve seen directives before; @media, @print. The @keyframes directive accepts a name and a block.

@keyframes heartbeat {
}

The block accepts any number of percentages which represent the stages of the animation across time.

@keyframes heartbeat {
  0%{
  }
  50%{
  }
  100%{
  }
}

The percentage blocks accept properties and values to change on the element being animated.

@keyframes heartbeat {
  0%{
    transform: scale(1.2);
  }
  50%{
    transform: scale(0.75);
  }
  100%{
    transform: scale(1.0);
  }
}

With the @keyframes defined one can use the animation.

.heart {
  animation-name: heartbeat;
  animation-duration: 2s;
}

The .heart element is given two animation properties. One to state what @keyframe to use and another to state the length of the animation.

Short hand can be used too.

.heart {
  animation: heartbeat 2s;
}

There are a number of other useful animation properties that can be used. I highly suggest using this excellent article from Thoughtbots.