Quick Tip: Animating height: auto;

Very often, applications rely on some kind of slide effect when toggling an element. This is quite common with things like accordions, where clicking on a heading toggles the following section open and closes all other sections. There you expect the opening section to start with a height of 0, and then expand to its full height. This state transformation is usually handled with a quick transition of the height property, in order to make the change less jarring to the user.

This all works fine when all sections have the same height. Then you can directly transition from height: 0; to height: xy;. If you don't know the sections height in advance, you might be tempted to transition to height: auto;, which doesn't really work.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis at purus consequat, fringilla turpis vel, blandit mi.

@keyframes height-auto {
  0% {
    height: 0;
  }

  100% {
    height: auto;
  }
}

The above example uses the height-auto animation. Clearly, no animation is happening. This is due to the fact that browsers can't handle the auto value. Now, the trick is to forget about height altogether, and instead focus on max-height.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis at purus consequat, fringilla turpis vel, blandit mi.

@keyframes height-max {
  0% {
    max-height: 0;
  }

  100% {
    max-height: 15em;
  }
}

The above example uses the height-max animation. Immediately, you'll notice that the box is now animated, yay! We don't need to know the element's actual height in advance, all we need is an estimate as to what the height could be.

What you want to do is animate to a max-height that you expect to be larger than your element. Of course, this involves a bit of guessing, but in many cases you'll be able to make those guesses pretty accurately. This way, you can handle multiple different elements and still have all of them take up just the space they need.

If you enjoyed reading this article you might want to share it on Twitter, on Facebook, or on Pinboard. For comments and questions, contact me through e-mail.