Skip to main content

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-property
  • transition-duration
  • transition-timing-function
  • transition-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.

Prompt
Create a page with a red 100x100px div that uses a CSS transition on the width property with a duration of 2 seconds. When the user hovers over the div, the width changes to 300px.
Output: complete HTML page

Transition property setup

styles.css
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.

Prompt
Create a page with a red 100x100px div that transitions multiple properties on hover: width to 300px over 2 seconds, height to 300px over 4 seconds, and background-color to blue over 3 seconds.
Output: complete HTML page

CSS Transition Properties

All the CSS transition properties are listed below:

  • transition — a shorthand that combines the four transition properties in a single property
  • transition-delay — how long (in seconds) the transition effect waits before it starts
  • transition-duration — how many seconds or milliseconds the transition effect runs for
  • transition-property — which CSS property the transition effect applies to
  • transition-timing-function — the speed curve that the transition effect follows