Using CSS Transitions to Animate a Button

Programmers

cssTransitionsWith CSS3 we got some pretty awesome new effects that we can use. One of my favorite is the transition effect. With one simple CSS line of code you can now animate items – all without using Javascript/jQuery.

Compatibility

The transitions work in most modern browsers, including IE10 and after. If it doesn’t work, though, no worries; it degrades gracefully, simply displaying the attributes without transitions.

Making It Work

You literally only need to add one line to your CSS:

transition: all .5s ease 0s;

Add that property to the normal state of the button/html element, to have it apply the transition to all properties that change. Let’s take a look at what’s happening in the basic form:

button {
    padding:10px 50px;
    border:1px solid #000;
    background:#fff;
    text-transform:uppercase;
    transition: all .5s ease 0s;
}
button:hover {
    background-color:#000;
    color:#fff;
    cursor:pointer;
}

Note the items that are changing on the hover: the background color and the text color. In the regular state for the button, we added the transition effect. Now, when you hover over the button, it will transition both the background color and the text color.

Check out the example below on jsFiddle:

Transition Property

The transition property is made up of 4 different elements.

Transition: [property name] [duration of transition] [timing effect] [delay before it starts];

There are a few things to keep in mind.

  • If you’re listing out the properties that are changing, include a comma at the end of the list (as shown below). The rest of the items don’t get commas in between them.
  • The duration of the transition can be in seconds (1s) or milliseconds (1000ms).
  • The timing effect can be one of the following: ease, linear, ease-in, ease-out, ease-in-out. It can also be cubic-bezier, but that’s a bit more complicated and beyond the scope of this article.
  • The delay before is starts is also in seconds or milliseconds. You can also do a negative number here, which means that when the user hovers over, it will jump that far into the transition before it starts. Example: -.5 seconds on a 1 second transition will cause the animation to jump to half-way through the animation before it starts.

Below is the example in jsFiddle:

Comments