CSS Trick #273..
Free Animation Energy.
Or.. How to get those neat animated indexes like at corz.org!
Here is a neat way to get some free animation energy out of your CSS.
Let's say you have an image that appears when a user hovers their mouse over a button link or whatever. Let's say it's a border. So you do something like this:
background: url("/img/myborder.png") no-repeat scroll center;
}
..it just "appears". Even if you add a nice transition..
transition: all 300ms ease-out 0s;
}
background: url("/img/myborder.png") no-repeat scroll center;
}
..it still just "appears". Albeit whilst flying alarmingly across the viewport. Ouch! Even if we fixed the crazy motion, this isn't what we're after
What if instead it grew from an infinitely small point in the centre and expanded out to full size over the transition period? Oh yes! That would look completely groovy! But how to get such impossibly groovy animation?
Remember that CSS transition animates the switch between two states. So what we do is, make the initial state a "non-state".
First, set the image in the regular (non-:hover
) state, and give it dimensions and a zero background size..
width: 12.8rem; /* don't forget to set the final size! */
height: 12.8rem;
transition: all 300ms ease-out 0s;
background: url("/img/myborder.png") no-repeat scroll center;
background-size: 0;
}
It can't be seen in this non-state, but sets a starting point for the transition. Then, all we need to set for the :hover
, is the size..
background-size: 100%;
}
Tada!
When the mouse hovers, the border grows out from nothing to fit the frame, and on mouse-out, sucks back in again, increasing and decreasing in opacity with each transition. Instant free animation which logically is right on spec! Also, it looks nice.
You can apply this technique to any :hover
(or whatever pseudo-selector) content, essentially, setting a zero-sized image in the non-hover state and setting the size in the changed state. The length of the transition is the animation time. Other interesting tweaks come to mind...
Or perhaps not. At any rate, it's a neat trick which might even work in Internet Explorer. Okay, it definitely doesn't work in Internet Explorer1, but still, a neat trick!
This is the final version, as used here..
for now..
;o) corz.org
References:
1 which is a real pity because in almost every other respect, Internet Explorer's transition performance is superior to just about every other browser out there. And don't get me started on how shoddy it makes all other browser's JavaScript (sorry, ECMAScript or whatever it's called) performance look. I mean, seriously? A Javascript scroll in IE is smooth and beautiful, in Firefox, *ugh*.