CSS: Transition
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
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.
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.
.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:
transition-property
transition-duration
transition-timing-function
transition-delay
- duration
-
- is a time spec, for example
3s
means 3 seconds. - If you want to use 0 second, you must write
0s
not just0
.
- is a time spec, for example
- 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:
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
.


What is the difference between CSS transition and animation?
- CSS transition just animate between 2 states, and need a trigger.
- CSS Animation allows one to control every key frame of animation, can loop, and can start when page load or any other event.