How to Set Transition Duration in CSS: Simple Guide
Use the
transition-duration property in CSS to set how long a transition animation takes. Specify the time in seconds (s) or milliseconds (ms), for example, transition-duration: 2s; makes the transition last 2 seconds.Syntax
The transition-duration property defines the length of time a CSS transition animation takes to complete. You can specify the time in seconds (s) or milliseconds (ms).
- Value: Time duration (e.g.,
2s,500ms) - Default:
0s(no transition)
css
transition-duration: 1s; /* or with milliseconds */ transition-duration: 500ms;
Example
This example shows a box that changes color smoothly over 1.5 seconds when you hover over it. The transition-duration controls how long the color change takes.
css
html, body {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background: #f0f0f0;
}
.box {
width: 150px;
height: 150px;
background-color: #3498db;
transition-property: background-color;
transition-duration: 1.5s;
transition-timing-function: ease;
border-radius: 8px;
cursor: pointer;
}
.box:hover {
background-color: #e74c3c;
}Output
A blue square box in the center of the page that smoothly changes to red over 1.5 seconds when hovered.
Common Pitfalls
Common mistakes include:
- Not specifying
transition-property, so the browser doesn't know which property to animate. - Using invalid time units or forgetting units (e.g., writing
transition-duration: 2;instead of2s). - Setting
transition-durationbut notransition-property, resulting in no visible effect.
Correct usage example:
css
/* Wrong: missing units and property */ .box { transition-duration: 2; /* invalid, missing 's' or 'ms' */ } /* Right: specify property and duration with units */ .box { transition-property: background-color; transition-duration: 2s; }
Quick Reference
| Property | Description | Example |
|---|---|---|
| transition-duration | Sets how long the transition lasts | transition-duration: 1s; |
| transition-property | Specifies which CSS property to animate | transition-property: background-color; |
| transition-timing-function | Controls the speed curve of the transition | transition-timing-function: ease; |
| transition-delay | Delays the start of the transition | transition-delay: 0.5s; |
Key Takeaways
Use
transition-duration with time units like s or ms to set animation length.Always specify
transition-property to tell which CSS property should animate.Forget units or missing properties cause transitions to not work.
Combine
transition-duration with other transition properties for smooth effects.Shorter durations make faster animations; longer durations make slower, smoother changes.