How to Transition on Hover in CSS: Simple Guide
To create a smooth change on hover in CSS, use the
transition property on the element and define the :hover style with the new property value. The transition property controls which CSS properties change smoothly and how long the effect takes.Syntax
The transition property in CSS defines how property changes happen smoothly over time. It has these parts:
- property: Which CSS property to animate (e.g.,
background-color,width). - duration: How long the transition lasts (e.g.,
0.3sfor 0.3 seconds). - timing-function: The speed curve of the transition (e.g.,
ease,linear). - delay: Optional wait time before the transition starts.
css
selector {
transition: property duration timing-function delay;
}
/* Example: */
button {
transition: background-color 0.3s ease;
}
button:hover {
background-color: blue;
}Example
This example shows a button that smoothly changes its background color and size when you hover over it.
css
button {
background-color: #4CAF50;
color: white;
padding: 1rem 2rem;
font-size: 1.25rem;
border: none;
border-radius: 0.5rem;
cursor: pointer;
transition: background-color 0.4s ease, transform 0.4s ease;
}
button:hover {
background-color: #45a049;
transform: scale(1.1);
}Output
A green button that smoothly changes to a darker green and grows slightly bigger when hovered.
Common Pitfalls
Common mistakes when using transition on hover include:
- Not specifying the
transitionproperty on the original element, so no smooth effect happens. - Trying to transition properties that cannot be animated, like
display. - Forgetting to include all properties you want to animate in the
transitionshorthand or usingallcarefully.
css
/* Wrong: transition only on hover - no smooth effect */ button:hover { background-color: red; transition: background-color 0.3s ease; } /* Right: transition on the button itself */ button { transition: background-color 0.3s ease; } button:hover { background-color: red; }
Quick Reference
Tips for smooth hover transitions:
- Always put
transitionon the normal state, not on:hover. - Use specific properties instead of
allfor better performance. - Use timing functions like
easeorlinearto control speed. - Combine multiple properties with commas.
Key Takeaways
Place the
transition property on the element's normal state to enable smooth changes on hover.Specify which CSS properties to animate and how long the transition lasts for clear effects.
Avoid animating non-animatable properties like
display.Use multiple properties in
transition separated by commas to animate more than one style.Choose appropriate timing functions like
ease for natural-looking transitions.