What is Transition in CSS: Simple Explanation and Example
transition in CSS is a way to make changes in CSS properties happen smoothly over time instead of instantly. It lets you control how long the change takes and the speed curve, making your webpage feel more natural and interactive.How It Works
Think of a CSS transition like a slow fade or slide instead of a sudden jump. When you change a style, such as color or size, the transition makes the change happen gradually over a set time. This is like turning a light dimmer switch slowly instead of flipping it on or off instantly.
Under the hood, CSS watches for changes on certain properties you specify. When a change happens, it animates the difference smoothly using the timing and duration you set. This helps users see the change clearly and makes the page feel polished and friendly.
Example
This example shows a button that changes its background color smoothly when you hover over it. The transition property controls the speed and easing of the color change.
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;
}When to Use
Use CSS transitions whenever you want to make changes on your webpage feel smooth and natural. They are great for hover effects on buttons, links, or images to give users feedback that something is interactive.
Transitions also help when showing or hiding elements, changing sizes, or adjusting colors, making the experience less jarring. For example, fading a menu in or out or smoothly resizing a card on hover improves user experience.
Key Points
- Transition controls how CSS property changes happen over time.
- You specify which properties to animate, how long it takes, and the speed curve.
- Commonly used for hover effects and smooth UI changes.
- Improves user experience by avoiding sudden jumps in style.