CSS3 slideToggle animation
What would we do without CSS3?
setInterval() to simply increase/decrease the passed property over time. For people using jQuery, this was even easier with built in functions like
slideToggle(). The latter is the one I had some trouble replicating with CSS.
The right tools for the job
In the example below the
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.