點燈坊

失くすものさえない今が強くなるチャンスよ

Building Accordion using Vue and TailwindCSS

Sam Xiao's Avatar 2022-01-08

Accordion is a common effect by toggling the element. We can implement it just by Vue and TailwindCSS without any package.

Version

Vue 3.2
TailwindCSS 3.0

Accordion

accordion000

<div> is toggled by accordion effect.

<script setup>
import { ref } from 'vue'

let isShow = ref(false)
let onToggle = () => isShow.value = !isShow.value
</script>

<template>
  <button class="text-gray-800 bg-gray-200 rounded-lg px-3 py-1" @click="onToggle">Toggle</button>
  <div class="transition-full duration-1000"
       :class="isShow ? 'max-h-screen overflow-auto' : 'max-h-0 overflow-hidden'">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus ea eos, error et illo ipsam iste nobis non obcaecati possimus qui ullam? Animi at consequuntur facere incidunt possimus quidem repellat!
  </div>
</template>
  • isShow : toggle isShow state to show <div>
  • transition-all : use transition-all effect
  • duration-1000 : set transition duration time
  • max-h-screen overflow-auto : show scroll bar if the content overflows with the height
  • max-h-0 overflow-hidden : content is hidden if the height is 0

Conclusion

  • The key point of the accordion is max-h-0 overflow-hidden to make content hidden when <div> is h-0