Transition Expand V2
10 May 2023

A little known feature when using CSS grid is that the grid-template-*** CSS property is animatable. This makes layout animation possible when using CSS grid! In this post we will use CSS grid and improve on the TransitionExpand component we created previously from this post.

A simpler TransitionExpand component

Here is the full source code for the updated TransitionExpand component. Notice the lack of Javascript calculation to achieve the effect. Just a prop to toggle the transition and TailwindCSS classes!

<script setup lang="ts">
withDefaults(
  defineProps<{
    isExpanded?: boolean;
  }>(),
  {
    isExpanded: true,
  },
);
</script>

<template>
  <div
    class="grid transition-[grid-template-rows_opacity]"
    :class="{
      'grid-rows-[0fr] opacity-0': !isExpanded,
      'grid-rows-[1fr]': isExpanded,
    }"
  >
    <div class="overflow-hidden">
      <slot />
    </div>
  </div>
</template>

Note!

  • the overflow-hidden can only apply to the child of the grid container and not the grid container itself, or else it wouldn’t work.
  • we are also animating the opacity, therefore we added the transition-[grid-template-rows_opacity] class to the container.
  • make sure the grid-template is animating from the same unit to the same unit i.e. fr to fr, or else it wouldn’t work. So if we were to use 0 to auto, it wouldn’t work.

Using TransitionExpand component

Here is an example usage of the TransitionExpand component.

<template>
  <button @click="show = !show">Toggle</button>

  <TransitionExpand :isExpanded="show"> ... </TransitionExpand>
</template>

Accordion Demo

Here is the same Accordion demo from the previous version but using the new TransitionExpand component which uses CSS Grid under the hood. Yay, lesser JavaScript code delivered to the client!

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Cum corporis repellendus excepturi nulla, quam dolor nihil repellat ipsum dignissimos voluptates blanditiis doloribus, fuga molestiae expedita cupiditate eius itaque similique quia.
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Cum corporis repellendus excepturi nulla, quam dolor nihil repellat ipsum dignissimos voluptates blanditiis doloribus, fuga molestiae expedita cupiditate eius itaque similique quia.

Conclusion

Its really nice to see modern CSS giving us frontend developers more reasons to smile about these days. With effects that were used to be JavaScript-only, we can now focus on other more important stuff when we code instead of spending time on how to achieve the desired effect with JavaScript!