Topic 32 of 41
<details> Accordions
Overview
Historically, creating a 'collapsible accordion' (often used in FAQ sections) required writing hundreds of lines of JavaScript to manage state, calculate heights, and toggle CSS classes. Modern HTML5 handles this completely natively using the <details> and <summary> tags. The browser automatically manages the open/closed state, provides a clickable triangle icon, and ensures full keyboard accessibility without a single line of JavaScript.
Syntax
html
<!-- The outer wrapper that holds the state -->
<details>
<!-- The clickable header (always visible) -->
<summary>What is your refund policy?</summary>
<!-- The hidden content (revealed when summary is clicked) -->
<div class="content">
<p>We offer a 100% money-back guarantee within the first 30 days.</p>
<p>No questions asked.</p>
</div>
</details>
<!-- Adding the 'open' attribute forces it to load already expanded -->
<details open>
<summary>Is this subscription recurring?</summary>
<p>Yes, you will be billed monthly.</p>
</details>Common Pitfalls
- Forgetting the
<summary>tag. If you don't provide a<summary>, the browser will generate a default one (usually saying 'Details'), completely confusing users who don't know what they are clicking. - Trying to heavily animate the opening/closing height natively. While the
<details>element is incredibly easy to use, animating the exact height transition purely in CSS is still notoriously difficult because it toggles thedisplayproperty, requiring advanced grid or flex hacks to smooth out.
Interview Questions
Q:
How do you style the small triangle icon that appears next to the
<summary>?A:
You can style or hide the default triangle icon by targeting the pseudo-element summary::marker in your CSS.
Real-World Example
A native HTML5 FAQ section.
example
html
<section class="faq-container">
<h2>Frequently Asked Questions</h2>
<details>
<summary>Do you offer student discounts?</summary>
<p>Yes! Verify your .edu email to receive 50% off.</p>
</details>
<details>
<summary>Can I cancel anytime?</summary>
<p>Absolutely. You can cancel your subscription from your dashboard.</p>
</details>
</section>Check Your Knowledge
Test your understanding of <details> Accordions with these quick questions.