⚡ CSS transition
— Animate Changes with Smooth Motion
The transition
property allows you to create smooth animations between different CSS property values. It’s the secret to beautiful UI effects like button hovers, modal fades, and smooth size or color changes — all without JavaScript.
🔹 What Does transition
Do?
Instead of an element instantly jumping from one state to another (e.g., when hovered), transition
makes the change happen gradually over time, giving a polished, animated feel.
📘 Syntax
selector {
transition: [property] [duration] [timing-function] [delay];
}
Each part is optional except the property and duration.
🧱 Breakdown of Parameters
Parameter | Description | Example |
---|---|---|
property | The CSS property to animate | background-color |
duration | Time the animation takes (e.g. 0.5s ) | 1s , 300ms |
timing-function | Easing curve (speed flow) | ease , linear |
delay | Wait time before transition starts | 0.2s , 500ms |
✅ Common Values
Timing Function | Effect |
---|---|
ease | Starts slow, speeds up, then slows |
linear | Constant speed |
ease-in | Starts slow, then speeds up |
ease-out | Starts fast, then slows down |
ease-in-out | Starts and ends slowly |
✍️ Example: Button Color Change on Hover
htmlКопироватьРедактировать<button class="fancy-btn">Hover Me</button>
.fancy-btn {
background-color: #3498db;
color: white;
transition: background-color 0.3s ease-in-out;
}
.fancy-btn:hover {
background-color: #2ecc71;
}
✅ The button color fades smoothly instead of switching instantly.
🖼️ Image Idea: Timeline Demo
Image Description:
Visual timeline showing:
- No transition: color changes instantly
- With transition: color fades over
0.3s
- Comparison of
ease
,linear
, andease-in-out
curves
🎯 Purpose: Show the feel of different transitions visually.
✨ Multiple Properties Example
.card {
transition: transform 0.5s ease, box-shadow 0.5s ease;
}
.card:hover {
transform: scale(1.05);
box-shadow: 0 10px 20px rgba(0,0,0,0.2);
}
✅ When hovered, the card zooms and casts a shadow smoothly.
🧠 Shorthand vs Longhand
✅ Shorthand:
transition: all 0.4s ease-in-out;
📝 Longhand:
transition-property: all;
transition-duration: 0.4s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
✅ Best Use Cases
Use Case | Transition Example |
---|---|
Button hovers | background-color , color , scale |
Modals/popups | opacity , transform , visibility |
Navigation highlights | border , color , box-shadow |
Form inputs | width , border , box-shadow |
🧪 Bonus Tip: Use with :hover
, :focus
, or JS Class Toggles
input:focus {
border-color: #2ecc71;
box-shadow: 0 0 5px #2ecc71;
}
Apply a transition
to these styles and they’ll animate in gracefully.
✅ Summary
Property | transition |
---|---|
Purpose | Smoothly animate property changes |
Parts | property , duration , timing , delay |
Works well with | hover , focus , :checked , class changes |
Combine with | transform , opacity , color , box-shadow , etc. |