How to Build an Accordion UI Component in HTML, CSS & JavaScript (Beginner Tutorial 2026)
Build a smooth, accessible accordion UI component in HTML, CSS and JavaScript — single-open logic, grid animation, keyboard support, tabs, search and dark mode. Free source code included.
Accordions are everywhere on the modern web. The FAQ section on a pricing page, the refund policy on a checkout screen, the chapter list of an online course, the settings panel of an app — all of them use the same pattern: a list of headings that expand to reveal content and collapse again when you are done. It is one of the most useful UI components a beginner can learn, because it teaches you HTML structure, CSS transitions and JavaScript state management in a single small project.
In this tutorial, you will build a complete, production-quality accordion in plain HTML, CSS and JavaScript — no framework, no library, no build step. It will open one panel at a time, animate smoothly, work with a keyboard, and announce itself correctly to screen readers. You will also learn the extras that turn a basic accordion into a component library: tabs, live search and a dark mode toggle. And if you would rather skip the build, you can download 20 ready-made accordion and tab components free from CodeFree at the end.
1. What an Accordion Actually Is (and Where You Will Use It)
An accordion is a vertically stacked list of sections. Each section has a header (usually a question or a title) and a hidden body. Clicking a header expands its body and collapses the others. The name comes from the musical instrument: the component folds and unfolds the same way.
Indian websites use accordions constantly. A coaching institute puts course fees and batch timings behind FAQ accordions. A D2C brand hides shipping, returns and COD details in them. A SaaS startup answers "Is GST included?" and "Can I cancel anytime?" without making the visitor scroll through a wall of text. The pattern works because it respects the reader's attention: show the questions, hide the answers until they are asked for.
Before writing code, decide the behaviour you want. The two big choices are:
- Single-open vs multi-open — should opening one panel close the others (FAQ style), or can several stay open at once (settings style)? Most FAQ pages use single-open; it keeps the page short and focused.
- Instant vs animated — a good accordion animates its height over 200–300 milliseconds. Instant toggling feels broken; a slow animation feels sluggish. Aim for around 250ms with an ease-out curve.
For this tutorial we will build a single-open accordion with a smooth animation, then add the extras. One file, three languages, about 100 lines of code.
2. Step 1: Build the HTML Structure
Good accordion HTML is semantic first. Each item is a container with a button for the header and a region for the body. Use a real <button> — never a <div> with a click handler — because buttons are keyboard-focusable and screen-reader friendly for free.
<div class="accordion">
<div class="accordion-item">
<h3>
<button class="accordion-header"
aria-expanded="false"
aria-controls="panel-1"
id="header-1">
What is your refund policy?
<span class="icon">+</span>
</button>
</h3>
<div class="accordion-panel"
id="panel-1"
role="region"
aria-labelledby="header-1">
<p>Full refunds within 7 days of purchase,
no questions asked. After that, a pro-rata
refund applies until day 30.</p>
</div>
</div>
<!-- repeat .accordion-item for each question -->
</div>
Notice the ARIA wiring: aria-expanded tells assistive technology whether the panel is open, aria-controls links the button to its panel, and role="region" with aria-labelledby links the panel back to its button. JavaScript will flip aria-expanded between true and false on every click. The <h3> wrapper keeps the document outline sensible — an FAQ page full of questions should read as headings, not as anonymous buttons.
Keep each panel's content short. If an answer needs more than three or four lines, it probably belongs on its own page, with the accordion linking to it. An accordion is a summary device, not a filing cabinet.
3. Step 2: Style It — the Smooth Height Animation
The classic beginner mistake is animating height: auto, which CSS cannot transition. The fix that every working accordion uses is one of two tricks: a large max-height value, or the modern grid-template-rows trick. The grid trick is cleaner, so we will use it.
.accordion-panel {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 0.25s ease-out;
}
.accordion-panel > * { overflow: hidden; }
.accordion-item.open .accordion-panel {
grid-template-rows: 1fr;
}
.accordion-header .icon {
transition: transform 0.25s ease-out;
}
.accordion-item.open .icon { transform: rotate(45deg); }
Here is what is happening: the panel is a one-row grid. Closed, the row is 0fr — zero height. Open, it becomes 1fr and grows to fit its content. Because grid-template-rows is animatable, the browser interpolates between the two and you get a buttery expand-and-collapse. The inner overflow: hidden stops the text from spilling out mid-animation. The + icon rotates 45 degrees into an ×, which is the universal "close me" signal — no JavaScript needed for the icon.
Style the headers like buttons that invite a click: full width, left-aligned text, generous padding (at least 16px), a subtle bottom border, and a visible hover background. Add a :focus-visible outline so keyboard users can see where they are. Indian users browse heavily on phones, so make the tap target at least 48px tall — small headers are the number-one reason mobile FAQ sections feel broken.
4. Step 3: Add the JavaScript — Single-Open Logic
The JavaScript is short, and that is the point. One click listener per header, one class toggle, one rule: when a panel opens, close the others.
document.querySelectorAll('.accordion-header')
.forEach(button => {
button.addEventListener('click', () => {
const item = button.closest('.accordion-item');
const isOpen = item.classList.contains('open');
// Close every panel first (single-open rule)
document.querySelectorAll('.accordion-item.open')
.forEach(openItem => {
openItem.classList.remove('open');
openItem.querySelector('.accordion-header')
.setAttribute('aria-expanded', 'false');
});
// Then open the clicked one — unless it was
// already open (clicking an open header closes it)
if (!isOpen) {
item.classList.add('open');
button.setAttribute('aria-expanded', 'true');
}
});
});
Two details matter here. First, the toggle behaviour: clicking an already-open header closes it, so the user is never trapped with a panel they cannot dismiss. Second, the aria-expanded updates happen in the same place as the class changes — if the visual state and the announced state ever disagree, screen-reader users get lied to, so keep them in one function.
Want multi-open instead? Delete the "close every panel" block and keep only the toggle. That is the entire difference — one of the reasons the accordion is such a good teaching project: a single design decision changes exactly one block of code.
5. Step 4: Make It Accessible — Keyboard and Screen Readers
Accessibility is not an extra feature; for a component made of buttons and hidden content, it is the component. A native <button> already gives you Tab focus and Enter/Space activation for free, which is why we used one in Step 1. Two additions finish the job.
First, arrow-key navigation. FAQ lists are long, and making a keyboard user press Tab through every header is slow. Add a keydown handler: ArrowDown moves focus to the next header, ArrowUp to the previous one, Home jumps to the first, End to the last. It is about ten lines of code and it is the difference between an accordion that is technically accessible and one that is actually pleasant to use.
Second, respect prefers-reduced-motion. Some users experience motion sickness from animations, and their operating system tells the browser about it. Honour it with one CSS rule:
@media (prefers-reduced-motion: reduce) {
.accordion-panel,
.accordion-header .icon {
transition: none;
}
}
Test the result with a keyboard only: Tab to the first header, press Enter to open it, use ArrowDown to move through the rest, and confirm every panel opens and closes. Then test with your phone's screen reader switched on for two minutes. If the accordion survives both, it is genuinely accessible — and that is a skill most junior developers never demonstrate in a portfolio.
6. Step 5: Level Up — Tabs, Live Search and Dark Mode
A single accordion is a good project. A small component library is a portfolio piece. The three upgrades below are the ones real products actually ship, and they all reuse the same ideas you just learned.
Tabs. An accordion stacks vertically; tabs switch horizontally. The mechanics are identical — one active item, the rest hidden — but the layout changes: buttons in a row, panels below, and the active tab gets an underline or a filled background. Many sites use both: tabs for big categories ("Pricing", "Shipping", "Returns") and an accordion inside each tab for the individual questions. Build the tab switcher with the same single-open logic from Step 3, swapping a class on the tab and its panel.
Live search. When an FAQ grows past ten items, add a search box that filters headers as the user types. The implementation is a one-liner at heart: on every keystroke, compare the input text with each header's text and hide the items that do not match. Show a "No results — try different words" message when everything is hidden, and reset the filter when the box is cleared. For an Indian audience, remember that users search in mixed language ("refund kaise milega", "GST invoice download") — match against the question text in lowercase and you will catch most of it.
Dark mode. A toggle that flips a data-theme="dark" attribute on the page, with CSS variables doing the rest: --bg, --text, --border and --accent swap values, and the whole accordion re-themes instantly, animation included. Persist the choice in localStorage so it survives a reload. These three upgrades — tabs, search, dark mode — are exactly what the free AccordionKit UI library below ships with, so you can see them working before you build your own.
7. Common Mistakes Beginners Make (and How to Avoid Them)
Animating height: auto. It does not transition; the panel snaps open. Use the grid-rows trick from Step 2, or a generous max-height if you need older-browser support — just remember that a max-height of 1000px on a 100px panel makes the animation feel delayed, because the transition runs across the full 1000px.
Using a <div> as the header. It is not focusable, not announced as a button, and breaks keyboard navigation. Always a real <button>. The same rule applies to tabs.
Forgetting aria-expanded. A screen reader user hears "button" and nothing else — they cannot tell whether the panel is open. Update the attribute in the same function that toggles the class.
Putting the whole answer in the accordion. If a panel needs a table, a form or five paragraphs, link out to a full page instead. Accordions are for short answers; long content inside them makes the page jump around as panels open and close.
Opening everything by default. Some beginners add open to the first item "so users see content". On a long FAQ this pushes everything else down the page. Start closed, or open only the single most-asked question — and only if analytics prove it is the one people want.
Get these five right and your accordion will feel like it came from a professional UI kit rather than a tutorial. Which brings us to the shortcut.
Frequently Asked Questions
Do I need a JavaScript framework to build an accordion?
No. A basic accordion needs about 20 lines of vanilla JavaScript, and this tutorial builds one with zero dependencies. Frameworks help when the accordion is part of a large app, but for a standalone component, plain HTML, CSS and JavaScript is faster to load and easier to debug.
How do I make only one accordion panel open at a time?
On every click, remove the open class from all panels first, then add it to the clicked panel (unless it was already open, in which case leave everything closed). That is the single-open rule in Step 3. Remove the "close all" step and you get multi-open behaviour instead.
Can I animate an accordion smoothly with pure CSS?
Yes — the modern way is the grid-template-rows: 0fr → 1fr trick shown in Step 2, which animates height without JavaScript measuring anything. The older max-height trick also works, but it can make short panels animate oddly if the max value is much larger than the content.
Is an accordion good for SEO?
Yes, if the content is in the HTML on page load. Search engines can read accordion content as long as it is present in the DOM and not loaded later via JavaScript. FAQ accordions are also a natural fit for FAQ schema markup, which can win your page a rich result in Google search.
Download the Finished Code — Free
You have just built the core of an accordion from scratch, and you understand every line of it. But when a client project needs the polished version — 20 ready-made accordion and tab styles, live search, copy-paste HTML buttons, dark mode and a pricing toggle — building it all again is a waste of a weekend.
That is why CodeFree ships AccordionKit UI — Accordion & Tabs Component Library as a free download: 20 copy-paste components in pure HTML, CSS and JavaScript, with the single-open logic, the grid-rows animation, keyboard navigation and dark mode already wired up. Download it, open index.html, copy the component you need, and drop it into your own project. It is free, it works offline, and it is the fastest way to ship a professional FAQ section, pricing toggle or settings panel on your next Indian client website.
Keep reading
How to Build a Payment Receipt Generator in JavaScript (Free Source Code, 2026)
Build a free payment receipt generator in JavaScript — amount in words (lakh/crore), auto receipt numbers, saved history and print-ready PDF. Full tutorial + free source code.
Read article
How to Build an Image Resizer in JavaScript: Canvas API Tutorial (Free Source Code)
Build your own image resizer in JavaScript with the Canvas API — aspect-ratio lock, quality control, format conversion and watermarking, step by step with free source code.
Read article
How to Build a Color Palette Generator in JavaScript: Harmony Modes, Lock & CSS Export (Free Source Code)
Build a colour palette generator in JavaScript with harmony modes, locked colours, copy-to-clipboard and CSS export — step-by-step tutorial with free source code.
Read article