Animating CSS

Animate the show/hide button with CSS in this lesson.

CSS is a powerful tool, and one of the powers it has is that many CSS properties can be animated. You can animate the color, position, even the shape of a CSS element. This gives you the ability to make your site more dynamic and interesting by just adding and removing CSS classes.

Three somewhat overlapping CSS concepts allow you to alter the display of existing CSS fields:

  • transform is a CSS property that instantly changes the values of other CSS properties by changing the size, position, or orientation of the element being drawn.
  • transition specifies a CSS property and a duration. When the specified property changes, the change happens gradually over the duration amount of time, rather than instantaneously.
  • animation is a more general form of a transition that allows you to specify multiple stopping points between the start and end value, as well as more complex timing and repeating behavior.

To show how these properties work, I’m going to go back to our original show-hide button on the schedule page of our app and turn it into something that looks more like the triangle widget in the MacOS finder—both the button and the text will gradually change their positions.

First, we need the image. I’ve put a raw image in app/javascript/images/arrow.svg.

Then, we need to adjust our view to display that image instead of the “Show” or “Hide” text. Here’s the change I’ve made to the button in the .erb file:

Get hands-on with 1400+ tech skills courses.