Card with Expand & Collapse Toggle

Elegantly show and hide additional content within a card using this interactive, animated expand and collapse component.

This is a highly versatile pattern for FAQs, showing detailed product information, or any situation where you want to keep the initial UI clean and allow users to reveal more content on demand.

Screenshot of multiple expandable cards, demonstrating an FAQ-style list.

Get Source Code Preview

About this Component

This component combines HTML, CSS, and JavaScript to create a functional and visually pleasing user experience. The JavaScript is designed to handle any number of these cards on a single page, each operating independently. Modern CSS techniques create a smooth animation without flickering or content jumps.

Features

Code Breakdown

HTML Structure

Each card requires a unique id on its main container, title, and collapsible content area. This is essential for the aria-controls and aria-labelledby attributes to work correctly, which creates a semantic link between the button and the content it controls for assistive technologies.

CSS Styling

The height animation uses CSS Grid. The collapsible container (.ecec-card-collapsible) is set to display: grid and has its grid-template-rows property animated from 0fr (zero fraction, or collapsed) to 1fr (one fraction, or expanded). The icon's rotation is handled by a simple CSS transform, which is toggled by the presence of an .is-open class on the main card.

JavaScript Logic

The script uses querySelectorAll()to find all card headers on the page and attach a click listener to each. When a header or its button is clicked, it uses .closest('.ecec-card') to find the specific parent card for that trigger. It then toggles an .is-open class on that specific card and updates its button's aria-expanded attribute. This instance-specific approach is what allows multiple cards to function independently.

Code

Here's the complete, self-contained code. Simply place the CSS, HTML, and JavaScript in your project as instructed. You can add or remove cards from the list as needed, ensuring each has a unique set of IDs.

View Output