CSS Tutorial - CSS3 transitions








With CSS3 transitions we can create animation by changing CSS properties.

We can control the time, from value, to value.

For example, we can change the color of an element from white to black, in one second.

The following table lists all the transition properties:

  • transition - A shorthand property for setting the four transition properties
  • transition-delay - Specifies when the transition effect will start
  • transition-duration - Specifies how many seconds or milliseconds a transition takes to complete
  • transition-property - Specifies the name of the CSS property the transition is for
  • transition-timing-function - Specifies the speed curve of the transition




Create an animation

To create animation with CSS3 transition, we have to specify two values:

  • the CSS property to change
  • the duration of the effect

The following code adds a transition effect on the width property, with a duration of 2 seconds.

We first sets the target property and duration.

div {
    -webkit-transition: width 2s; /* For Safari 3.1 to 6.0 */
    transition: width 2s;
}

If the duration part is not specified, the default value is 0, and there would be no transition.

The we have to trigger the property change. The following code uses mouse-over event to trigger animation on an element.

div:hover {
    width: 300px;
}

Here is the complete source code. Hover over the div element above, to see the transition effect.

<!DOCTYPE html>
<html>
<head>
<style> 
div {<!--from   w ww . j  av a2 s. c  o m-->
    width: 100px;
    height: 100px;
    background: black;
    -webkit-transition: width 2s;
    transition: width 2s;
}

div:hover {
    width: 300px;
}
</style>
</head>
<body>

<div>Hi</div>

</body>
</html>

Click to view the demo





Multiple values in transitions

We can add transition effects for more than one CSS property by separating the properties with a comma.


<!DOCTYPE html>
<html>
<head>
<style> 
div {<!--from   ww  w  . ja va  2s  . c o  m-->
    width: 100px;
    height: 100px;
    background: black;
    -webkit-transition: width 2s, height 2s, -webkit-transform 2s;
    transition: width 2s, height 2s, transform 2s;
}

div:hover {
    width: 200px;
    height: 200px;
    -webkit-transform: rotate(180deg);
    transform: rotate(180deg);
}
</style>
</head>
<body>
    <div>Hover me to see the transition effect!</div>
</body>
</html>

The code above is rendered as follows:

Property Description CSS
transition-delay Delay before the transition3
transition-duration Set the duration of the transition3
transition-property Set the name of the CSS property in the transition effect3
transition-timing-function Set the speed curve of the transition effect3
transition Shorthand property for setting the four transition properties3