Published at
Updated at
Reading time

Did Chris just publish a post and unveil the solution to a long-lasting CSS problem almost in a side sentence? It seems like it!

What of the many are we walking about? We're talking about animating (or transitioning) an element's height from 0 to something (auto) just with CSS. That's right โ€“ this is possible in all modern browsers today. No JavaScript required!

Animated grid rows

Not too long ago, browsers shipped animatable CSS grid columns and rows which you could use to fly in a side menu or do fancy stuff like Michelle Barker. ๐Ÿ‘‡

I've never considered using animated grid rows to hide grid cells, though.

Here's the CSS trick to transition or animate an element's height to auto:

  1. define a grid container
  2. define a single grid row with 0fr
  3. add a transition for grid-template-rows
  4. set overflow: hidden to the one element inside the grid
  5. redefine the grid-template-rows to be 1fr with a CSS class or attribute selector
.grid {
  display: grid; /* 1 */
  grid-template-rows: 0fr; /* 2 */
  transition: grid-template-rows 0.5s ease-in-out; /* 3 */
} {
  grid-template-rows: 1fr; /* 5 */

.grid-inner {
  overflow: hidden; /* 4 */

And voila! You can now animate an element's height without any hardcoded values. It's just CSS โ€” toggle a class and call it a day! CSS Grid figures out all the rest.

I. Am. Blown. Away!

Zero-height elements come with accessibility issues because their content can still be reached with assistive technology. The example above implements a mix of aria-hidden, aria-controls and aria-expanded to work around the issues.

Accessibility is tough, though, and I'm no expert. If you have any feedback on the implementation, let me know!

But to Chris' point, even though this technique works, it'd be nice to have an easier way to animate element heights in CSS. I 100% agree but for now, I'll take this approach because it's the best we got! Thanks Chris! ๐Ÿ’ฏ

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 8 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles