Loading
Current section: Implementation 12 exercises
lesson

Use CSS Grid to Animate Elements with Dynamic Height

Currently we are animating to a fixed height of 100px on hover since browsers can't animate from 0 to auto:


<p class="h-0 overflow-hidden text-white/70 transition-all group-hover:h-[100px]">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minima quia ipsa
eius.
</p>

Luckil

Loading lesson

Transcript

00:00 And so here comes the cool trick, we're going to use CSS Grid to achieve this, and it's a pretty simple trick actually. We're going to use the <fr> unit, animate it from 0 <fr> to 1 <fr>. I will wrap

00:14 my <p> tag in a <div> with a class of <grid>. Let's move the paragraph inside of it. And I'm going to get rid of the height of 0 and then 100 pixels on hover. So we're back to everything showing. And

00:31 you know what? The spacing missing here is annoying me, so I'll add the empty 2 again, and we'll work that out later. Empty 2 here. So now we're going to make this grid row, we're going to make this 0 <fr> and then 1 <fr> on group hover. So on the parent grid here, we're going to set a

00:49 custom grid rows, which is grid template rows, we're going to just have 0 <fr>. So it basically creates one row of 0 <fr>, which is going to be nothing. And now the text is gone and hidden.

01:04 And here on group hover, we can change this to grid rows and 1 <fr>. So we're animating from 0 <fr> to 1 <fr> and I can move the transition-all class in this element. So let's take a look.

01:21 That's a super handy trick. It works well and it's pretty easy to implement.