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:

<span class="button js--day-button"
      data-action="click->day-toggle#toggle">
  <span data-day-toggle-target="buttonText"
        class="background-arrow">
  </span>
</span>

The inner span element is still the buttonText target, but now it has a CSS class of background-arrow and it doesn’t have the show or hide text. In fact, it seems to have no content at all. Where’s the image?

We’re going to define that background image in the CSS, in the pack/application.scss file, start with this:

.background-arrow {
  background-image: url("../images/arrow.svg");
  width: 25px;
  height: 25px;
}

This displays the image as part of the CSS style.

We’re using the background-image CSS property rather than an HTML img tag. In general, you’d use background-image for purely decorative elements, elements you don’t want to print, and elements you don’t need to show up in indexing or SEO. I realize these images don’t have any text, but img tags have titles and alt-text, and those get indexed for search. This example is not clearly one or the other—it’s decorative, but you might want, say, a screen reader to find it.

Here’s the button with the image before we animate it:

Get hands-on with 1200+ tech skills courses.