CSS Transitions
CSS transitions allows you to change property values smoothly (from one value to another), over a given duration.
How to Use CSS Transitions?
To create a transition effect, you must specify two things:
- the CSS property you want to add an effect to
- the duration of the effect
Note: If the duration part is not specified, the transition will have no effect, because the default value is 0.
The following example shows a 100px * 100px red <div> element. The <div> element has also specified a transition effect for the width property, with a duration of 2 seconds:
div { width: 100px; height: 100px; background: red; -webkit-transition: width 2s; /* Safari */ transition: width 2s; }
The transition effect will start when the specified CSS property (width) changes value.
Now, let us specify a new value for the width property when a user mouses over the <div> element:
div:hover { width: 300px; }
Specify the Speed Curve of the Transition
The transition-timing-function
property specifies the speed curve of the transition effect.
The transition-timing-function property can have the following values:
ease
- specifies a transition effect with a slow start, then fast, then end slowly (this is default)linear
- specifies a transition effect with the same speed from start to endease-in
- specifies a transition effect with a slow startease-out
- specifies a transition effect with a slow endease-in-out
- specifies a transition effect with a slow start and endcubic-bezier(n,n,n,n)
- lets you define your own values in a cubic-bezier function
The following example shows the some of the different speed curves that can be used:
#div2 {transition-timing-function: ease;}
#div3 {transition-timing-function: ease-in;}
#div4 {transition-timing-function: ease-out;}
#div5 {transition-timing-function: ease-in-out;}
Delay the Transition Effect
div { width: 100px; height: 100px; background: red; -webkit-transition: width 3s; /* Safari */ -webkit-transition-delay: 1s; /* Safari */ transition: width 3s; transition-delay: 1s; } div:hover { width: 300px; }
Transition + Transformation
div { width: 100px; height: 100px; background: red; -webkit-transition: width 2s, height 2s, -webkit-transform 2s; /* Safari */ transition: width 2s, height 2s, transform 2s; } div:hover { width: 300px; height: 300px; -webkit-transform: rotate(180deg); /* Safari */ transform: rotate(180deg); }
div { transition-property: width; transition-duration: 2s; transition-timing-function: linear; transition-delay: 1s; }
div { transition: width 2s linear 1s; }