Transitions
CSS transitions smoothly animate a property's change over time, turning abrupt state changes — like a hover colour swap — into polished, gradual effects.
The transition Shorthand
A transition needs a property to animate, a duration, and (optionally) a timing function describing its acceleration curve. Without a transition declared, property changes happen instantly.
.btn {
background: #0a0a0a;
color: #fff;
padding: 12px 24px;
border-radius: 6px;
transition: background 0.2s ease, transform 0.2s ease;
}
.btn:hover {
background: #00cc44;
transform: translateY(-2px);
}
Common Mistakes
- Setting transition: all, which can accidentally animate properties you didn't intend to, and hurts performance slightly.
- Forgetting to declare the transition on the base state, not just the hover state, causing it to only animate one direction.
- Choosing a duration that's too slow (over ~400ms) for simple UI feedback, which starts to feel sluggish.
- Trying to transition properties that cannot be animated, like display, which has no intermediate states.
Professional Tip
List specific properties in your transition rule (e.g. transition: background 0.2s, transform 0.2s;) rather than all. It's more predictable, performs better, and documents exactly what's meant to animate.
Your Turn
Create a button with a smooth colour and slight upward transform on hover, and a card that gently increases its box-shadow when hovered.
Mini Quiz
What happens to a CSS property change if no transition is declared for it?
transition declaration, CSS property changes apply immediately with no animation — transitions must be opted into.