Table of Contents
Creating an interactive pricing accordion is a popular way to display multiple pricing options on a website. Using CSS Flexbox combined with JavaScript, you can design a responsive and user-friendly accordion that expands and collapses sections smoothly.
Understanding the Basic Structure
The core of a pricing accordion consists of multiple panels, each representing a pricing tier or plan. These panels are stacked vertically and can be expanded or collapsed by clicking on their headers.
Designing with Flexbox
Flexbox provides a flexible layout system that makes it easy to align and distribute space among items in a container. For the accordion, Flexbox ensures that the panels are stacked neatly and can adapt to different screen sizes.
Set the container to display as flex and use the flex-direction property to stack items vertically:
display: flex;
flex-direction: column;
HTML Structure of the Accordion
The HTML consists of a series of div elements for each panel, with a header and content section:
<div class="accordion">
<div class="panel">
<div class="header">Basic Plan</div>
<div class="content">Details about the Basic Plan...</div>
</div>
<div class="panel">
<div class="header">Pro Plan</div>
<div class="content">Details about the Pro Plan...</div>
</div>
<div class="panel">
<div class="header">Enterprise Plan</div>
<div class="content">Details about the Enterprise Plan...</div>
</div>
</div>
Styling the Accordion with CSS
Apply Flexbox styles to the container and style each panel for clarity. For example:
.accordion {
display: flex;
flex-direction: column;
width: 100%;
max-width: 600px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 4px;
overflow: hidden;
}
.panel {
display: flex;
flex-direction: column;
border-bottom: 1px solid #ccc;
}
.header {
background-color: #f7f7f7;
padding: 15px;
cursor: pointer;
font-weight: bold;
}
.content {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
padding: 0 15px;
}
.content.open {
max-height: 200px; /* or set to auto with JavaScript for dynamic height */
padding: 15px;
}
Adding Expand/Collapse Functionality with JavaScript
JavaScript toggles the open class on the content div when the header is clicked, enabling expand and collapse effects.
document.querySelectorAll('.header').forEach(function(header) {
header.addEventListener('click', function() {
const content = this.nextElementSibling;
content.classList.toggle('open');
});
});
Putting It All Together
Combine the HTML, CSS, and JavaScript into your webpage. Ensure to include the CSS styles within a <style> tag or stylesheet, and the JavaScript within a <script> tag or external script file. This setup creates a responsive, flexible pricing accordion that users can interact with to view different plans easily.
By leveraging Flexbox, you ensure that your accordion layout remains adaptable across devices, providing a seamless user experience.