The curious behavior of CSS transitions, for some intents, has been sort of the elephant in the room: Everyone is just so glad to finally have them, that they don't want to complain or talk about these confusing feelings. One such cause for provocation is the way the CSS transition behavior changes when separating mouse on and off states. When just a mirrored in and out effect wont do, we desire more control.

Let's look at a bare-minimum CSS hover transition:

Transitions in, transitions out as expected by CSS3's behavior.

Now, the oddities begin when looking to separate two state effects, one for on/in, one for off/out:

Notice that in the CSS code, we've added the border-width transition in the :hover, not the .ex2 main class -- with the background transition. Yet, the border still transitions. It does so against the logic of what makes sense in the CSS world. (Side point: a hover transition does make more logical sense to go in the :hover pseudo-element, but CSS3 has told us hover transitions go in the main class.)

Experiment: Let's flip the transitions, placing the border-width in the .ex2b initial class, and the background in the :hover.

As expected, if considering the last quirky example, our border-width transition applies upon hovering OFF. It's still backwards in our CSS universe, but we're seeing some sense of it, at least. From these behaviors, we can deduce this: To separate states, a hover OFF transition should be placed in the class declaration, and hover ON behavior should be placed in the :hover declaration. I emphasize this, because it really isn't straightforward. It's just sort of some animation behavior you would eventually stumble upon or figure out after banging your head a few times.

Let's combine what we know into a more practical reason for doing any of this:

Control achieved!

Things to observe and take away:

When you have one instance -- e.g. for both on/off behaviors -- of a transition for an element, your transition properties are in the main class declaration.

When you have differential on/off effects, your hover ON transition is in the :hover pseudo-element declaration, and your hover OFF transition is in the main class declaration.

We live in strange times.

1,932 4 20