CSS: Transition

By Xah Lee. Date: . Last updated: .

What is CSS Transition

CSS transition creates smooth animation of change of CSS values.

How to Trigger Transition

Transition is activated when a CSS property value changes or HTML element state change via CSS: Pseudo-Class Selectors, e.g. :focus :hover etc.

You can also use JavaScript to change CSS property. e.g. JS: Fade a Element Using CSS Transition

Example: Simple Transition

HOVER ME

on touch screen, touch and hold is mouse hover.

Code

.xtran634 {
 border: solid thick red;
 width: 30%;
 transition: width 1s;
}

.xtran634:hover {
 width: 100%;
}

Example: Multiple Transitions

You can specify transition for multiple CSS properties.

HOVER ME

Code

.xmultitran {
 width: fit-content;
 overflow-wrap: normal;
 border: solid thick red;
 padding: 8px;
 text-align: center;

 width: 90px;
 height: 90px;
 border-radius: 0;
 box-shadow: 0 0 black;

 transition: width 1s, height 1s, border-radius 1s, box-shadow 1s;
}

.xmultitran:hover {
 width: 200px;
 height: 200px;
 border-radius: 20px;
 box-shadow: 20px 20px 20px gray;
}

Here, we are changing the element's size, border-radius, and box-shadow.

Example: Transition Color

Hover or touch and hold following boxes.

red to yellow
.redtoyelo {
 padding: 8px;
 margin: 8px;
 width: 6rem;
 transition: background-color 1s linear;
 background-color: red;
}

.redtoyelo:hover {
 background-color: yellow;
}

CSS Transition Syntax

Syntax

transition: spec1, spec2, spec3

Each of the spec can have this form:

cssPropertyName duration timingFunction delay

The transition attribute is a short form for several other ones:

duration
  • is a time spec, for example 3s means 3 seconds.
  • If you want to use 0 second, you must write 0s not just 0.
timingFunction

controls how the values change over time.

Some predefined values you can use are:

  • ease
  • ease-in
  • ease-out
  • ease-in-out
  • linear
  • step-start
  • step-end
  • steps(integer, start)
  • steps(integer, end)
  • cubic-bezier(number, number, number, number)

The default is ease.

delay

time before the transition begin. e.g. 0.5s for 0.5 second.

Transition Timing Function

timing_function controls how the value changes over time.

predefined values you can use are:

The default is ease.

step
Step timing function
TimingFunction
Bézier Timing Function Control Points

What is the difference between CSS transition and animation?

CSS, Transform, Animation