How to Use CSS Transition Shorthand for Smooth Effects
Use the
transition shorthand property in CSS to define which properties to animate, the duration, timing function, and delay all in one line. The syntax is transition: property duration timing-function delay;, where you can omit parts to use defaults.Syntax
The transition shorthand combines multiple transition properties into one line:
- property: The CSS property to animate (e.g.,
background-color,width). - duration: How long the transition lasts (e.g.,
0.5sfor half a second). - timing-function: The speed curve of the transition (e.g.,
ease,linear). - delay: How long to wait before starting the transition (e.g.,
0sor1s).
You can omit timing-function and delay to use default values.
css
transition: property duration timing-function delay;Example
This example shows a button that changes its background color smoothly when you hover over it using the transition shorthand.
css
button {
background-color: #3498db;
color: white;
padding: 1rem 2rem;
border: none;
border-radius: 0.5rem;
cursor: pointer;
transition: background-color 0.3s ease-in-out;
}
button:hover {
background-color: #2ecc71;
}Output
A blue button that smoothly changes to green when hovered over.
Common Pitfalls
Common mistakes when using transition shorthand include:
- Forgetting to specify the
property, which defaults toalland can cause unwanted animations. - Using invalid time units (always use
sfor seconds ormsfor milliseconds). - Not matching the property you want to animate exactly (e.g.,
backgroundvsbackground-color).
Here is a wrong and right example:
css
/* Wrong: missing property, causes all properties to animate */ .box { transition: 0.5s ease; } /* Right: specify property explicitly */ .box { transition: background-color 0.5s ease; }
Quick Reference
| Part | Description | Example |
|---|---|---|
| property | CSS property to animate | background-color |
| duration | How long the animation lasts | 0.3s |
| timing-function | Speed curve of the animation | ease-in-out |
| delay | Wait time before animation starts | 0s |
Key Takeaways
Use the transition shorthand to combine property, duration, timing-function, and delay in one line.
Always specify the property to avoid animating all properties unintentionally.
Duration must include time units like seconds (s) or milliseconds (ms).
Timing function controls the speed curve and can be omitted for default ease.
Delay is optional and defaults to 0 seconds if not set.