Artboard 16light, inspiration, solution, idea, innovation,ionicons-v5_logosGoogle Sheets iconSwift icon
Published at
Updated at
Reading time
2min

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 an element's height from 0 to something (auto).

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 trick to toggle an element's height:

  1. define a grid element
  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;
  grid-template-rows: 0fr;
  transition: grid-template-rows 0.5s ease-in-out;
}

.grid.open {
  grid-template-rows: 1fr;
}

.grid-inner {
  overflow: hidden;
}

And voila! You can now transition an element's height, and it doesn't use any hardcoded values โ€“ 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, it'd be nice to have an easier way to animate element heights. Word! For now, I'll take this approach, though! Thanks Chris! ๐Ÿ’ฏ

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 3 days ago.

Related Topics

Related Articles