[CSS] 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>

 

Luckily there's a handy trick we can use to get around this limitation!

wrap the paragraph with a div containing a class of grid, and set the grid row to 0fr. Then we can then animate the grid row to 1fr on hover and the transition-all class from the paragraph to the new grid div:

<div class="grid grid-rows-[0fr] transition-all  group-hover:grid-rows-[1fr]">
	<p class="mt-2 overflow-hidden text-white/70">
		Lorem ipsum dolor sit, amet consectetur adipisicing elit. Minima quia ipsa
		eius.
	</p>
</div>

 

Using the fractional unit fr for the sizing is the trick that makes this work. It's a flexible unit of measurement for CSS Grid that distributes the available space evenly among the rows and columns.

In our case, setting the grid row to 0fr will hide the paragraph since it's a zero height row. Then, when we hover over the card, we change the grid row to 1fr, which will reveal the paragraph and have it take up all available space.

posted @ 2024-06-04 15:05  Zhentiw  阅读(3)  评论(0编辑  收藏  举报