How to Create Fade Out Animation in CSS Easily
To create a fade out animation in CSS, use the
@keyframes rule to change opacity from 1 to 0. Then apply this animation to an element with the animation property specifying duration and easing.Syntax
The fade out animation uses @keyframes to define the change in opacity from fully visible to invisible. The animation property applies this effect to an element with timing and repetition settings.
@keyframes fadeOut: Defines the animation steps.from { opacity: 1; }: Start fully visible.to { opacity: 0; }: End fully transparent.animation: fadeOut 2s ease forwards;: Runs the animation over 2 seconds, easing smoothly, and keeps the final state.
css
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
.element {
animation: fadeOut 2s ease forwards;
}Example
This example shows a blue box that fades out smoothly over 3 seconds when the page loads.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Fade Out Animation Example</title> <style> @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } } .box { width: 150px; height: 150px; background-color: #007BFF; animation: fadeOut 3s ease forwards; } </style> </head> <body> <div class="box" aria-label="Blue box fading out"></div> </body> </html>
Output
A solid blue square box that gradually becomes invisible over 3 seconds after the page loads.
Common Pitfalls
Common mistakes when creating fade out animations include:
- Not using
forwardsin theanimationproperty, which causes the element to revert to visible after fading out. - Forgetting to set the initial
opacityto 1, which can cause the animation to start invisible. - Using
display: noneinstead of opacity, which removes the element immediately without animation.
css
/* Wrong: animation resets after finishing */ .element { animation: fadeOut 2s ease; } /* Right: animation keeps final state */ .element { animation: fadeOut 2s ease forwards; }
Quick Reference
Remember these key points for fade out animations:
- Use
@keyframesto animateopacityfrom 1 to 0. - Apply
animationwith duration, easing, andforwardsto keep the fade out effect. - Ensure the element is visible before animation starts.
- Use semantic HTML and ARIA labels for accessibility.
Key Takeaways
Use @keyframes to animate opacity from 1 to 0 for fade out effects.
Include 'forwards' in animation to keep the element invisible after fading.
Set initial opacity to 1 to ensure the element starts visible.
Avoid using display:none for fade out as it skips animation.
Add ARIA labels and semantic HTML for better accessibility.