How to Transition Opacity in CSS: Simple Guide with Examples
To transition opacity in CSS, use the
transition property with opacity as the property to animate. For example, transition: opacity 0.5s ease; smoothly changes opacity over half a second when it changes.Syntax
The transition property controls how CSS property changes animate over time. It has three main parts:
- Property: The CSS property to animate, e.g.,
opacity. - Duration: How long the animation lasts, e.g.,
0.5sfor half a second. - Timing function: The speed curve of the animation, e.g.,
easefor smooth start and end.
css
selector {
transition: opacity 0.5s ease;
}Example
This example shows a box that fades out when you hover over it by changing its opacity from 1 to 0.5 smoothly over 0.5 seconds.
css
html, body {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background: #f0f0f0;
}
.box {
width: 150px;
height: 150px;
background-color: #007BFF;
opacity: 1;
transition: opacity 0.5s ease;
border-radius: 8px;
cursor: pointer;
}
.box:hover {
opacity: 0.5;
}Output
A blue square in the center of the page that smoothly becomes semi-transparent when hovered over.
Common Pitfalls
Common mistakes when transitioning opacity include:
- Not specifying
transitionon the element before the change, so no animation happens. - Trying to transition a property not supported by
transition. - Using shorthand
transitionbut forgetting to includeopacityas a property.
Example of a wrong and right way:
css
/* Wrong: No transition property set, so opacity changes instantly */ .box { opacity: 1; } .box:hover { opacity: 0.5; } /* Right: Transition set to animate opacity smoothly */ .box { opacity: 1; transition: opacity 0.5s ease; } .box:hover { opacity: 0.5; }
Quick Reference
Tips for smooth opacity transitions:
- Always set
transitionon the element before the state change. - Use
opacityas the property intransition. - Choose a duration that feels natural, usually between 0.3s and 0.7s.
- Use timing functions like
easeorlinearfor different effects.
Key Takeaways
Use the CSS property 'transition' with 'opacity' to animate opacity changes smoothly.
Set the transition on the element before the opacity changes to see the effect.
Choose a duration and timing function that create a natural fade effect.
Without 'transition', opacity changes happen instantly with no animation.
Common mistake: forgetting to include 'opacity' in the transition property.