CSS Transitions Explained

By Dave Ceddia Comment

CSS Transitions Explained

As programmers, we like to think in “steps.” Do this, then do that. When X happens, do Y. At least if we’re not writing functional-style code, anyway ;)

So when you need to animate some element on a web page, the natural first thought is to think of it in terms of cause and effect - when the user hovers over this button, then animate it enlarging slightly.

Now, if you’ve tried to actually do this with the CSS transition property, you know that’s not how it works. CSS transitions are declarative. You tell the browser what you want, and it takes care of the rest.

This clashes with the imperative, step-based nature of programming. When does the transition happen? How do I decide what gets animated?

Somehow, despite all the tutorials I had read, I missed one very critical thing about how CSS transitions work. The key is that you are telling the browser,

"Whenever this property changes, apply that change slowly."

The property transition: width 2s says “when the width changes, animate it over the course of 2 seconds.”

transition: all 0.5s says “when anything changes, spend 0.5s doing it.”

So if you want to round the corners of a button when it’s hovered?

/* Initial state: border-radius is 0.
 * When border-radius changes, it'll take 0.3s
 * instead of happening immediately */
button {
	border-radius: 0;
	transition: border-radius 0.3s;
	/* any other styles you need ... */
button:hover {
	border-radius: 20px;

Here’s the button:

I hope this helped clear up the “how” behind CSS transitions!

Learning React can be a struggle -- so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, read my book Pure React.

Best thing that ever happened to my career 👏🏽

I’m very happy I bought this. Didn’t fully grasp the fundamentals from Udemy courses I’ve been taking. I’m buying the Redux course immediately after I’m done with this. THANK YOU SOO MUCH

– Oluwafemi
comments powered by Disqus