CSS3 slideToggle animation

Before CSS3 was widely supported we had to call on Javascript to do some of the animation work. Because of this, a lot of Javascript libraries have built-in functions to do stuff that isn’t necessarily Javascript’s job. Time for CSS3 to take over!

What would we do without CSS3?

Up until recently we relied on Javascript to take care of animation. I wrote a function that I included in most of my projects. It accepts an element pointer, a CSS property to animate and a speed at which to animate. It uses a simple setInterval() to simply increase/decrease the passed property over time. For people using jQuery, this was even easier with built in functions like fadeIn(), slideIn() and slideToggle(). The latter is the one I had some trouble replicating with CSS.

The right tools for the job

In March 2013, Louis Lazaris gave a great presentation at jquery.to on what I think is the right way of animating using Javascript and CSS.

Louis uses simple Javascript logic to add and remove classes when needed, and lets CSS take it from there. An element that needs animation gets a transition property to animate to new values in a pre-defined CSS class.

In the example below the div elements height property is set to 100 pixels as soon as the element gets the .expanded class assigned. The transition property makes the change happen more smoothly.

But, CSS requires us to animate from one absolute value to another. The problem is that, well, this is the web and we don’t always know how high a particular element is going to be.

Mimicking jQuery’s slideToggle()

When jQuery executes the slideToggle() command it gets the expanded height value from the target element so that it can slide back open to that height later on. CSS, however, doesn’t have those capabilities.

The trick here is to manipulate the max-height property instead of the height. In the Fiddle below I’m manipulating the max-height property to “allow” the box to be that tall.

To play it safe I usually set the max-height to double what I think it will be. That way, when it’s subject to change, it won’t break when content is added or removed. Since we are now animating the max-height to such a high value, we also have to double the transition duration to keep the transition smooth.

Conclusion

By using CSS as opposed to Javascript animation, we can not only keep our Javascript cleaner by getting rid of all the presentational stuff, but in some browsers we can even see some performance benefits, since some browsers will use the graphics card for CSS animation.