What is transition?

A CSS transition smoothly animates a property from its old value to its new value when that value changes, for example on :hover, :focus, or when JavaScript toggles a class. You specify which properties to transition, the duration, the timing function and an optional delay: transition: background-color 200ms ease, transform 200ms ease;.

Properties

  • transition-property: which properties (all is convenient but can animate things you did not intend).
  • transition-duration: 150ms to 300ms feels responsive for UI.
  • transition-timing-function: ease, ease-in-out, linear, cubic-bezier(.2, .8, .2, 1), steps().
  • transition-delay.
  • transition-behavior: allow-discrete: lets discrete properties like display and overlay participate, enabling exit animations.

Transition vs animation

TransitionAnimation
Needs a state change to startCan start automatically
Two states: from A to BAny number of keyframes
Runs once per changeCan loop and alternate
Great for hover, focus, open/closeGreat for loaders, attention effects, sequences

Entry animations

Elements appearing (e.g. from display: none) have no "before" state; @starting-style { opacity: 0; } supplies it, so new elements can fade in with only transitions.

Best practices

  • Transition transform and opacity for smooth, GPU-friendly motion.
  • Put the transition on the base state so it animates both in and out.
  • Use transitionend in JavaScript to run code after the effect.
  • Shorten or remove transitions under prefers-reduced-motion.

Code example

html
1<style>
2 body { font-family: system-ui; display: flex; gap: 16px; align-items: start; flex-wrap: wrap; }
3 .btn {
4 padding: 10px 18px; border: 2px solid #0b1020; border-radius: 10px; background: #ffd84d; font-weight: 700;
5 box-shadow: 4px 4px 0 #0b1020;
6 transition: transform 150ms ease, box-shadow 150ms ease, background-color 200ms;
7 }
8 .btn:hover { transform: translate(-2px, -2px); box-shadow: 6px 6px 0 #0b1020; background: #fde047; }
9 .btn:active { transform: translate(2px, 2px); box-shadow: 0 0 0 #0b1020; }
10 .panel {
11 width: 220px; padding: 12px; border: 2px solid #0b1020; border-radius: 10px; background: white;
12 transition: opacity 250ms, transform 250ms, display 250ms allow-discrete;
13 }
14 .panel.hidden { opacity: 0; transform: translateY(-8px); display: none; }
15 @starting-style { .panel { opacity: 0; transform: translateY(-8px); } }
16 @media (prefers-reduced-motion: reduce) { * { transition-duration: 1ms !important; } }
17</style>
18<button class="btn" onclick="panel.classList.toggle('hidden')">Toggle panel</button>
19<div class="panel hidden" id="panel">I fade and slide in and out, including display: none.</div>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app