CSS Transition

By Tony 9.1.2024


Almost all the websites out there have some kind of animation or transition to make its user experience smooth, engaging, and appealing. Today, we'll learn how to create smooth transitions on your webpage using CSS transition.

transition: background-color 0.5s 1s ease;

To create a smooth change when an element’s style is changed, we use the transition property. For example, there's a blue box that turns red when you hover over it. Without a transition, the color change happens instantly. But with a transition, the color gradually shifts from blue to red, creating a smooth effect. The first value we see in the example above is background-color. This tells the browser to only smooth out the transition of the element's background color when it's changing. If you want all the element's styles to have a transition, use the "all" value. The next value, 0.5s, defines the transition duration, or how long the transition is from start to finish. The third value, 1s, is transition delay, which tells the browser to wait for 1 second before starting the transition. The final value, ease, sets the timing of the transition. It can be linear, curved, or following a certain math function. In this case, the value "ease" tells the browser to start the transition slowly, then speed it up near the end.

HTML
CSS
JavaScript
Output

As you can see in the example above, if you hover over the red box and wait for 1 second, it shifts from red to blue smoothly over a 0.5 second period. If your cursor leaves the box again, it will wait 1 second and smoothly change back to red over a 0.5 second period again. This is because transition applies both ways, not only when you start hovering over an element, but also when you exit the element. To fully understand how transition works, you can change the transition duration value to something like 3s so you can see the change happen slowly, or try out different values and timing. Have fun exploring transitions!