Table of Contents
Creating an interactive FAQ section on your website can greatly enhance user experience. Using CSS Flexbox combined with smooth transitions allows for a sleek, responsive, and dynamic accordion feature. This guide will walk you through building a FAQ accordion with Flexbox that expands and collapses smoothly.
Understanding Flexbox Basics
Flexbox is a CSS layout module that makes it easy to design flexible responsive layout structures. It aligns and distributes space among items in a container, even when their size is unknown or dynamic. For a FAQ accordion, Flexbox helps in aligning questions and answers neatly and allows for smooth expansion and collapse.
HTML Structure of the FAQ Accordion
Each FAQ item consists of a question and an answer. The question acts as a toggle, and the answer expands or collapses based on user interaction. Here is a simple HTML structure:
<div class="faq-item">
<button class="faq-question">What is Flexbox?</button>
<div class="faq-answer">
<p>Flexbox is a CSS layout module that provides an easy way to align and distribute space among items in a container.</p>
</div>
</div>
CSS Styling for Flexbox Accordion
Apply Flexbox styles to the FAQ container and items. Use transitions for smooth opening and closing animations. Here’s an example CSS:
.faq-item {
display: flex;
flex-direction: column;
border: 1px solid #ccc;
margin-bottom: 10px;
border-radius: 4px;
}
.faq-question {
background-color: #f7f7f7;
padding: 15px;
cursor: pointer;
border: none;
text-align: left;
font-size: 16px;
}
.faq-answer {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
padding: 0 15px;
}
.faq-answer.open {
max-height: 200px; /* or a large enough value to fit content */
padding: 15px;
}
JavaScript for Interactive Behavior
Use JavaScript to toggle the open class on the answer div when the question button is clicked. This triggers the CSS transition for smooth expansion and collapse.
document.querySelectorAll('.faq-question').forEach(button => {
button.addEventListener('click', () => {
const answer = button.nextElementSibling;
answer.classList.toggle('open');
});
});
Complete Example
Combine all parts into your webpage or Gutenberg block editor. Include the HTML structure, CSS styles within a <style> tag, and the JavaScript within a <script> tag. This creates a fully functional, animated FAQ accordion using Flexbox.