How to animate an element's height with CSS grid
- 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 (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!
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
:
- define a grid container
- define a single grid row with
0fr
- add a transition for
grid-template-rows
- set
overflow: hidden
to the one element inside the grid - redefine the
grid-template-rows
to be1fr
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.open {
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! ๐ฏ
Join 5.5k readers and learn something new every week with Web Weekly.