In jQuery, how do I animate the "max-height" CSS property?

I ran into the same thing.

The answer is to use "maxHeight" rather than "max-height" ...


This question is getting a bit old, but here's how I solved it using basic jQuery, in case someone else needs a simple solution.

In my case, I have a list of blog posts which are first rendered to the page with a max-height which only shows the first 4 lines of text, the rest being overflow: hidden. I have a expand/collapse button which toggles the article from its collapsed form to expanded (fully displayed) and back again.

At first I tried animating the max-height property directly and, as you've discovered above, this won't work. I also tried this with css transitions with the same disappointing result.

I also tried just setting it to a very large number like '1000em', but this made the animations look dumb as it was literally interpolating to such a large value (as you'd expect).

My solution uses scrollHeight, which is used to determine the natural height of each story once the page is loaded as follows:

$(function(){ // DOM LOADED

  // For each story, determine its natural height and store it as data.
  // This is encapsulated into a self-executing function to isolate the 
  // variables from other things in my script.
  (function(){

    // First I grab the collapsed height that was set in the css for later use
    var collapsedHeight = $('article .story').css('maxHeight');

    // Now for each story, grab the scrollHeight property and store it as data 'natural'        
    $('article .story').each(function(){
      var $this = $(this);

      $this.data('natural', $this[0].scrollHeight);
    });

    // Now, set-up the handler for the toggle buttons
    $('.expand').bind('click', function(){
      var $story = $(this).parent().siblings('.story').eq(0),
          duration = 250; // animation duration

      // I use a class 'expanded' as a flag to know what state it is in,
      // and to make style changes, as required.  
      if ($story.hasClass('expanded')) {
        // If it is already expanded, then collapse it using the css figure as
        // collected above and remove the expanded class
        $story.animate({'maxHeight': collapsedHeight}, duration);
        $story.removeClass('expanded');
      }
      else {
        // If it is not expanded now, then animate the max-height to the natural
        // height as stored in data, then add the 'expanded' class
        $story.animate({'maxHeight': $story.data('natural')}, duration);
        $story.addClass('expanded');
      }
    });

  })(); // end anonymous, self-executing function

});

To do the same with images, I would just wrap them in an outer div which is what you'll set the max-height and overflow:hidden on, just like I used div.story above.