Animating the height of content using CSS grid | Kevin Powell

A useful trick for animating the height of a specific piece of content. You cannot transform a height in CSS to the auto keyword; you have to provide a fixed value, which is obviously suboptimal in most situations. Kevin's trick is to use grid row heights and the fr unit (which is animatable) to create the illusion of height manipulation.

The general code looks like this (though you'd probably use a JavaScript event to trigger the expansion, rather than hover):

<style>
    section {
        display: grid;
        grid-template-rows: 0fr;
        transition: grid-template-rows 500ms;
    }

    section > div {
        overflow: hidden;
    }

    section:hover {
        grid-template-rows: 1fr;
    }
</style>

<section>
    <div>
        <h2>Title</h2>
        <p>Content goes here</p>
    </div>
</section>

The trick here is really the overflow property (and I did find it was possible to tweak this back to auto or scroll, but it's less smooth).

In testing, yes you can animate multiple rows in different ways, use other keywords like max-content, and generally play around with this technique quite a lot. Though there may be dragons; Chrome in particular does weird things with Grid animations if there are multiple rows, and you can't tweak timing that much (though you can use keyframe animation to do a similar thing and tweak timing there, again with caveats and Chrome weirdness).

Explore Other Notes

Older

Nuclear anchored sidenotes

I have long sought a web-native way to achieve sidenotes with CSS, and it turns out Eric is in the same boat. The new Anchor Position API in CSS is seeking to solve that problem, and whilst it […]
  • A useful trick for animating the height of a specific piece of content. You cannot transform a height in CSS to the auto keyword; you have to provide a fixed value, which is obviously suboptimal in [&#8230;]
  • Murray Adcock.
Journal permalink

Made By Me, But Made Possible By:

CMS:

Build: Gatsby

Deployment: GitHub

Hosting: Netlify

Connect With Me:

Twitter Twitter

Instagram Instragram

500px 500px

GitHub GitHub

Keep Up To Date:

All Posts RSS feed.

Articles RSS feed.

Journal RSS feed.

Notes RSS feed.