Networks

Animating CSS height to auto

A common problem with responsive design is the need to animate with CSS an element who’s dimensions are unclear. It’s straight forward to set height:0px in one rule, height:100px in another, add some transition: all 1s and Bob’s your mother’s brother, but what if the height of your element varies per breakpoint? What if you can’t control the content of the element?

css-tricks.com has had a few snippets/editorials on this, but their solutions tend to expect the animation to be done with jQuery.animate(). What if you want to do it with CSS? My quick and dirty jQuery solution is as follows:

Basically you’ve got an element .my-element on which some javascript toggles the class .open. Without that class, the element is closed, or invisible, with zero height. With .open added, the element shows its contents at whatever height is required.