Tailwind CSS Q&A Logo
Tailwind CSS Q&A Part of the Q&A Network
Q&A Logo

How can I create a collapsible accordion with Tailwind and minimal JavaScript?

Asked on Sep 17, 2025

Answer

To create a collapsible accordion using Tailwind CSS with minimal JavaScript, you can utilize Tailwind's utility classes for styling and a small amount of JavaScript to toggle the visibility of the content. Here's a simple example:
<!-- BEGIN COPY / PASTE -->
    <div class="accordion">
      <button class="accordion-header bg-blue-500 text-white p-3 w-full text-left" onclick="toggleAccordion(event)">
        Accordion Header
      </button>
      <div class="accordion-content hidden p-3 bg-gray-100">
        <p>This is the content of the accordion.</p>
      </div>
    </div>

    <script>
      function toggleAccordion(event) {
        const content = event.currentTarget.nextElementSibling;
        content.classList.toggle('hidden');
      }
    </script>
    <!-- END COPY / PASTE -->
Additional Comment:
  • Use Tailwind's "hidden" utility to initially hide the accordion content.
  • The JavaScript function "toggleAccordion" toggles the "hidden" class to show or hide the content.
  • Ensure the button and content are styled using Tailwind classes for a consistent look.
  • This example uses inline JavaScript for simplicity; consider external scripts for larger projects.
✅ Answered with Tailwind CSS best practices.

← Back to All Questions
The Q&A Network