How to Use CSS Transition for Smooth Effects
Use the
transition property in CSS to smoothly animate changes between property values. Specify which CSS properties to animate, the duration, timing function, and delay to control the effect.Syntax
The transition property controls how CSS property changes animate over time. It has four parts:
- property: Which CSS property to animate (e.g.,
background-color,width). - duration: How long the animation lasts (e.g.,
0.5sfor half a second). - timing-function: The speed curve of the animation (e.g.,
ease,linear). - delay: How long to wait before starting the animation (optional).
You can write all parts together or use individual properties like transition-property and transition-duration.
css
selector {
transition: property duration timing-function delay;
}
/* Example: */
button {
transition: background-color 0.3s ease 0s;
}Example
This example shows a button that changes its background color smoothly when you hover over it. The transition makes the color change take 0.5 seconds with an ease timing.
css
button {
background-color: #3498db;
color: white;
padding: 1rem 2rem;
border: none;
border-radius: 0.5rem;
cursor: pointer;
transition: background-color 0.5s ease;
}
button:hover {
background-color: #2ecc71;
}Output
A blue button that smoothly changes to green when hovered over.
Common Pitfalls
Common mistakes when using transition include:
- Not specifying which property to transition, causing no animation.
- Trying to animate properties that can't be transitioned (like
display). - Forgetting to add
transitionon the element's normal state, so the animation doesn't trigger. - Using very short durations that make the transition hard to notice.
Here is a wrong and right example:
css
/* Wrong: transition only on hover - no animation on hover out */ button:hover { transition: background-color 0.5s ease; background-color: #2ecc71; } /* Right: transition on button itself */ button { transition: background-color 0.5s ease; } button:hover { background-color: #2ecc71; }
Quick Reference
Here is a quick summary of the transition property parts:
| Part | Description | Example |
|---|---|---|
| property | CSS property to animate | background-color, width, opacity |
| duration | How long the animation lasts | 0.3s, 1s |
| timing-function | Speed curve of animation | ease, linear, ease-in-out |
| delay | Wait time before animation starts | 0s, 0.5s |
Key Takeaways
Always set the transition on the element's normal state, not just on hover or active.
Specify which CSS property you want to animate for the transition to work.
Use durations long enough (like 0.3s or more) to see the smooth effect clearly.
Not all CSS properties can be transitioned; avoid properties like display or position.
Use timing functions like ease or linear to control the animation speed curve.