I want to add Tailwind classes to animate the opening and closing of the accordion in the code below. I’ve added all the classes, but it doesn’t have any animation. How can I achieve what I want?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Accordion Example</title>
<script>
function toggleAccordionContent(element) {
const content = element.nextElementSibling;
if (content.classList.contains('hidden')) {
content.classList.remove('hidden');
content.classList.remove('max-h-0', 'opacity-0');
content.classList.add('max-h-screen', 'opacity-100');
} else {
content.classList.add('hidden');
content.classList.add('max-h-0', 'opacity-0');
content.classList.remove('max-h-screen', 'opacity-100');
}
}
</script>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css"
rel="stylesheet"
/>
</head>
<body>
<div id="accordion" class="space-y-4">
<!-- Accordion Item -->
<div
class="group accordion-item-wrapper example-class border border-gray-300 rounded-lg"
>
<div
role="button"
class="accordion-summary block w-full p-4 transition-all duration-300 ease-in-out example-summary-class bg-gray-100 hover:bg-gray-200 cursor-pointer"
onclick="toggleAccordionContent(this)"
>
<!-- Chevron or other content goes here -->
<span class="font-semibold">Accordion Title</span>
</div>
<div
data-collapse="collapse-1"
class="hidden custom-accordion-content overflow-hidden transition-all duration-700 ease-in-out max-h-0 opacity-0 example-content-class"
>
<div class="p-4 bg-white">
<!-- Content goes here -->
<p>
This is the content inside the accordion. You can place any HTML
content here.
</p>
</div>
</div>
</div>
<!-- Repeat above block for additional accordion items -->
</div>
</body>
</html>
2
Answers
You can create custom animations in
tailwindcss
inside yourtailwind.config.js
configuration file. To do this, follow the instructions in the documentation.Example for a
wiggle
animation :Transitions do not play on the same frame that an element’s
display
gets changed from/tonone
.Instead, you could consider applying
visibility: hidden
. This still hides the element’s descendents from the element tree (i.e. accessibility tree, focus order, interactivity, etc.) but allows transitions to play.