Animate div with max-height using CSS and jQuery
May 11th 2017

Recently we ran into an annoying problem. Say you have a div with some dynamic text. Sometimes the text is short, so should be displayed in its entirety. Other times - it’s too long, so should be partly hidden. However, differently from hiding the text completely and then using jQuery’s .slideDown() of simply .show(), we wanted to display first few lines of it and give user the ability to show the rest. Also, and this part is very important - the revealing of the whole text should be animated (sort of the .slideDown() effect).

All seems fairly simply until you start using ’max-height’ property. As it turns out it completely disables possibility of using the .slideDown() function as well as any other jQuery animation. Max-height of course is necessary if you would like not to set static content height and rather use ’up to’ measure. Say we would like to display up to 5 lines of text (which is about 100px height in our scenario) and hide the rest of text, if any. This would work just fine with ’height’ parameter and also would enable us to animate it with jQuery. However, should the text be only a single line, it would have an unnecessary gap underneath (the remaining 80px in our case). However, if you change ’height’ to ’max-height’, the problem solves itself. Everything up to 100px height is visible, the rest is hidden.

So what do we do to achieve the desired animation? Use a bit of CSS animations with some JavaScript. Here’s how we solved our headache in one complete file: 

We have also prepared a jsFiddle so you can see it in action. By the way the fiddle also contains a sample code to check if the div has any hidden text. If not, it hides the expanding button as it is no longer needed.

That’s all for this time. Happy coding and we hope we saved some Ibuprofen for our fellow developers out here.

Back To Blog