CSS Transitions
Overview
Transitions provide smooth mathematical interpolation between two distinct states (e.g., changing from blue to red when hovered). Without a transition, the change happens instantly in 0 milliseconds, which feels harsh and jarring. Transitions require a triggering event (like :hover, :focus, or JavaScript adding an .active class) to start.
Syntax
/* The Shorthand: transition: [property] [duration] [easing-function] [delay] */
.btn {
background-color: blue;
transform: scale(1);
/* Tell the browser to smoothly animate ANY changes to these properties */
transition: background-color 0.3s ease, transform 0.2s linear;
}
.btn:hover {
/* State B: The browser mathmatically generates all the frames in between! */
background-color: red;
transform: scale(1.1);
}Common Pitfalls
Using
transition: all 0.3s. This forces the browser to aggressively monitor and calculate animations for every single property on the element, utterly destroying rendering performance on complex pages. Always explicitly list the exact properties you want to transition.Placing the
transitiondeclaration on the:hoverstate instead of the base state. If you put it on:hover, the animation will smoothly scale up when hovered, but instantly snap back to size 0 when the mouse leaves. Put it on the base class so it animates both in and out.
Interview Questions
What is an 'easing function' (like ease-in-out)?
It dictates the acceleration curve of the animation. linear moves at a constant robotic speed. ease-in-out starts slowly, accelerates in the middle, and gently decelerates at the end, mimicking real-world physics.
Real-World Example
A beautifully smooth hover effect utilizing cubic-bezier for a 'spring' bounce.
.card {
transform: translateY(0);
/* Uses a custom bezier curve to slightly 'overshoot' and bounce back! */
transition: transform 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.card:hover {
transform: translateY(-10px); /* Lifts the card up */
}Check Your Knowledge
Test your understanding of CSS Transitions with these quick questions.