CSS Grid Enables Auto Height Transitions

Nelson Menezes has published a new approach to a long-standing CSS limitation, and it is remarkably clever.

CSS has never been able to animate to auto dimensions. Going from zero to "as tall as the content needs to be" would be useful in many situations, and the existing techniques have been well documented. They come down to two options:

  • Transitioning max-height to a value larger than required, which makes the easing timing imprecise and the animation janky.
  • Measuring the final size with JavaScript and animating to that value, which means relying on JavaScript.

Menezes' method avoids both of those, and it is not one of the transform-based hacks that produce awkward visuals either. Its core is CSS Grid.

.expander {
  display: grid;
  grid-template-rows: 0fr;
  transition: grid-template-rows 1s;
}

.expander.expanded {
  grid-template-rows: 1fr;
}

What happens next is hard to believe: in Firefox, content inside that area transitions between 0 and its natural height. A few additional details are needed, such as hiding overflow and managing visibility, so it looks right while remaining accessible.

To get Chrome on board, the recommendation is to add stars to the relevant Chromium issue. Better still, of course, would be native support for auto height transitions, which does not seem entirely out of reach.