CSS Transitions Basics

What CSS Transitions Do

A transition smoothly animates a property from its old value to its new value over a set duration, instead of the change happening instantly - typically triggered by a state change like :hover or a class toggle.

The transition Shorthand

.btn {
  background: #1d4ed8;
  transition: background 0.2s ease;
}
.btn:hover {
  background: #1e40af;
}

The shorthand order is: property duration timing-function delay. Here, only the background property animates, over 0.2 seconds, easing smoothly rather than moving at a constant speed.

Transitioning Several Properties at Once

.card {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

Multiple properties can be listed, each with its own timing, separated by commas - or transition: all 0.3s ease; can animate every property that changes, though listing specific properties is usually better for performance.

Not Every Property Can Be Transitioned

Only properties with values that can be smoothly interpolated between two states can transition - numbers, colors, sizes and positions all work. A property like display cannot transition smoothly, since block and none have no meaningful "halfway" value.

A Common Mistake

/* Wrong: transition declared on the hover state does nothing useful */
.btn:hover {
  transition: background 0.2s ease;
  background: #1e40af;
}

The transition property should be declared on the base/default state, not only on the :hover state - otherwise the transition back to normal on mouse-out will not be smooth.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.