CSS Transitions
CSS transitions allow you to animate changes to CSS properties smoothly over time, enhancing the user experience without JavaScript.
1. Basic Syntax
Use the transition
property to define which CSS property to animate, the duration, and optionally, the timing function and delay.
.button {
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #3498db;
}
2. Transition Properties
transition-property
: Which property to animatetransition-duration
: How long the transition takestransition-timing-function
: Easing (e.g.,ease
,linear
,ease-in
)transition-delay
: Delay before starting
.box {
transition-property: transform;
transition-duration: 0.5s;
transition-timing-function: ease-in-out;
transition-delay: 0s;
}
3. Shorthand Transition
Combine all properties into one line:
.card {
transition: transform 0.4s ease-in-out;
}
.card:hover {
transform: scale(1.05);
}
4. Multiple Transitions
Animate more than one property at the same time:
.box {
transition: opacity 0.3s ease, transform 0.5s ease-in;
}
5. Best Practices
- Keep transitions smooth and subtle for better UX.
- Avoid animating properties that trigger reflows (like
width
,height
) unless necessary. - Use
transform
andopacity
for performance-friendly animations.
Conclusion
CSS transitions are a powerful way to bring your website to life with smooth animations. Theyβre easy to use and work well with user interactions like hover and focus.