Last Updated: September 29, 2021
·
78.3K
· ultimatedelman

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.

2 Responses
Add your response

As much as this does work, I wouldn't recommend it for production sites where content is dynamic and changes without developer influence. I've used it enough times to come up against issues of content being hidden where the max-height wasn't set high enough. Also setting the value too high makes the transition time meaningless

over 1 year ago ·

In case of dynamic content you should compute actual height of content, e.g. like this:
http://codepen.io/kriede/pen/RVYXZW

over 1 year ago ·