mn2a2g
Last Updated: January 21, 2017
·
38.96K
· ultimatedelman
0e2e822d32a7ab3d7f0b7098d03b1d16

How to Use CSS Transitions for height and width from 0px to auto

Scenario 1

You have an element that you want to expand from height: 0 to whatever its natural height is. You'd prefer to use CSS, but everyone knows that you can't transition to height: auto;, so you resort to using .slideDown(). This is fine, but now you have to co-ordinate your CSS with your JS to make sure everything is timed correctly between the two and that they happen on the same call every time you make a class change and...

Scenario 2

You have a list of inline-block elements that you'd like to grow horizontally with a nice, smooth transition. You could do this if you set the width property, but you don't want them all to be the same size. Sure, you could write some JS to create a clone element, measure the width, and set the style attribute but... no.

It's a pain.

Instead of doing all this, you can "abuse" the max-height and max-width properties. They are threshold properties, meaning that they will allow the element to go up to a certain value, but no further. They are also animatable. So, if you set the max- property to something you know the box won't grow larger than, you can animate it!

Here's a demo showing both a max-width and max-height example.

Caveat

When you set a max- property, at least as of this writing, the animation takes place as though the element was that size to start, meaning a potential delay of the animation. Therefore it is recommended that if you have a contracting animation (ie, you want the element to hide again), you size your max- property as close to the actual size you want as possible. This is demonstrated in the fiddle link above with the two red boxes. Notice how the small red box doesn't actually start shrinking until the large red box is at the same place.