CSS Transitions
With CSS transitions, the values of a property move smoothly to their new state over a set amount of time.
The CSS transition Property
A transition effect needs just two things: which CSS property to animate, and how long the change should last.
Both can be set with transition, a shorthand for four properties:
transition-propertytransition-durationtransition-timing-functiontransition-delay
In the example below, a 100px by 100px <div> element has a 2-second transition effect on its width property.
A change to the properties of the element is what starts a transition, and pseudo-classes like :hover, :active, :focus, or :checked often cause that change.
Once the cursor leaves the element, the original style comes back gradually.
Example
Hovering over the <div> widens it to 300px, and the change happens smoothly.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Transition on Hover</title>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
transition: width 2s;
}
div:hover {
width: 300px;
}
</style>
</head>
<body>
<h1>CSS Transition on Hover</h1>
<p>Mouse over the div element below, to see the transition effect:</p>
<div></div>
</body>
</html>
Transition property setup
div {
width: 100px;
height: 100px;
background-color: red;
transition: width 2s;
}
Change Multiple Property Values
Commas separate the properties when several of them transition at the same time.
In the example below, width, height, and background-color each get a transition with its own duration.
Example
Width takes 2 seconds here, height takes 4 seconds, and background-color takes 3 seconds.
Output: complete HTML page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Transition Multiple Properties</title>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
transition: width 2s, height 4s, background-color 3s;
}
div:hover {
width: 300px;
height: 300px;
background-color: blue;
}
</style>
</head>
<body>
<h1>CSS Transition - Multiple Properties</h1>
<p>Mouse over the div element below, to see the transition effect for multiple properties:</p>
<div></div>
</body>
</html>
CSS Transition Properties
All the CSS transition properties are listed below:
transition— a shorthand that combines the four transition properties in a single propertytransition-delay— how long (in seconds) the transition effect waits before it startstransition-duration— how many seconds or milliseconds the transition effect runs fortransition-property— which CSS property the transition effect applies totransition-timing-function— the speed curve that the transition effect follows