CSS Transitions


When the value of a CSS property changes, the rendered result is usually changed almost instantly. On mouse hover, for example, changing the background color of a button is a common example. When you put the cursor over the button in a typical scenario, the background color of the button switches from the old property value to the new property value almost instantly.

CSS3 adds a new transformation function that allows you to seamlessly animate a property from its previous value to its new value over time. The following example demonstrates how to animate the background-color of an HTML button while it is hovered over with the mouse.



button {
  background: #fd7c2a;
  /* For Safari 3.0+ */
  -webkit-transition-property: background;
  -webkit-transition-duration: 2s;
  /* Standard syntax */
  transition-property: background;
  transition-duration: 2s;
}
button:hover {
  background: #3cc16e;
}

Live Demo!


Output:

To make the transition happen, you must use the transition-property CSS property to specify the name of the CSS property to which you want to apply the transition effect, and the transition-duration CSS property to specify the duration of the transition effect (greater than 0). All other transition properties, on the other hand, are optional because their default values do not preclude a transition from occurring.


Multiple Transitions Execution


Each of the transition properties may have multiple values separated by commas, making it simple to define multiple transitions with different settings at the same time.



button {
  background: #fd7c2a;
  border: 3px solid #dc5801;
  /* For Safari 3.0+ */
  -webkit-transition-property: background, border;
  -webkit-transition-duration: 1s, 2s;
  /* Standard syntax */
  transition-property: background, border;
  transition-duration: 1s, 2s;
}
button:hover {
  background: #3cc16e;
  border-color: #288049;
}

Live Demo!


Output:


Property of Transition Shorthand


When it comes to transitions, there are a lot of things to remember. To make the code shorter, all of the transition properties can be defined in a single property.

The transition property is a shortcut for setting all of the individual transition properties (transition-property, transition-duration, transition-timing-function, and transition-delay) in the defined order at once.

When using this property, it's critical to keep the values in this order.



button {
  background: #fd7c2a;
  -webkit-transition: background 2s ease-in 0s; /* For Safari 3.0+ */
  transition: background 2s ease-in 0s; /* Standard syntax */
}
button:hover {
  background: #3cc16e;
}

Live Demo!