HTML: Building Interactive Accordions with the `details` and `summary` Elements

Written by

in

In the world of web development, creating engaging and user-friendly interfaces is paramount. One common UI element that significantly enhances the user experience is the accordion. Accordions allow you to neatly organize content, providing a clean and concise layout that reveals information on demand. This tutorial will guide you through building interactive accordions using the HTML5 `details` and `summary` elements, offering a clear, step-by-step approach for beginners to intermediate developers. We will explore the core concepts, provide practical examples, and address common pitfalls to ensure you can confidently implement accordions in your web projects. This tutorial is designed to help you not only understand the functionality but also to optimize your code for search engines, ensuring your content is accessible and easily discoverable.

Understanding the `details` and `summary` Elements

The `details` and `summary` elements are native HTML5 elements designed to create interactive widgets that users can open and close to reveal additional content. They provide a simple, semantic, and accessible way to implement accordions without relying heavily on JavaScript. This approach not only simplifies the coding process but also improves the overall performance and accessibility of your web pages.

The `details` Element

The `details` element acts as a container for the hidden content. It represents a disclosure widget from which the user can obtain additional information. By default, the content within the `details` element is hidden. The element is opened or closed by the user interacting with the `summary` element.

The `summary` Element

The `summary` element provides a visible heading or title for the `details` element. This is the text the user clicks to toggle the visibility of the content within the `details` element. It acts as the control that opens and closes the accordion section. Without a `summary` element, the `details` element will not have a visible control.

Basic Structure of an Accordion

The basic structure of an accordion using `details` and `summary` is straightforward. Here’s a simple example:

<details>
  <summary>Click to expand</summary>
  <p>This is the content that will be revealed when you click the summary.</p>
</details>

In this example, the text “Click to expand” is the title displayed by default. When the user clicks on it, the paragraph containing “This is the content that will be revealed when you click the summary.” will become visible.

Step-by-Step Guide to Building an Accordion

Let’s build a more practical accordion with multiple sections. Here’s how to do it step-by-step:

Step 1: HTML Structure

First, create the HTML structure for your accordion. You can wrap the entire accordion in a container, such as a `div`, to help with styling. For each section of your accordion, use the `details` and `summary` elements.

<div class="accordion-container">
  <details>
    <summary>Section 1: Introduction</summary>
    <p>Content for section 1 goes here.</p>
  </details>

  <details>
    <summary>Section 2: Core Concepts</summary>
    <p>Content for section 2 goes here.</p>
  </details>

  <details>
    <summary>Section 3: Advanced Techniques</summary>
    <p>Content for section 3 goes here.</p>
  </details>
</div>

Step 2: Basic Styling with CSS

While the `details` and `summary` elements provide the basic functionality, you’ll likely want to style them to match your website’s design. Here’s some basic CSS to get you started:


.accordion-container {
  width: 80%;
  margin: 20px auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden; /* Important for border-radius to work correctly */
}

summary {
  padding: 10px;
  background-color: #f0f0f0;
  cursor: pointer;
  font-weight: bold;
  list-style: none; /* Removes the default bullet point */
}

summary::-webkit-details-marker {  /* For Chrome, Safari, and newer versions of Edge */
  display: none;
}

summary::marker {  /* For Firefox and other browsers */
  display: none;
}

details[open] summary {
  background-color: #ddd;
}

details p {
  padding: 10px;
  margin: 0;
  border-top: 1px solid #ccc;
}

This CSS sets up a container, styles the summary elements with a background color and a pointer cursor, and removes the default marker. The `details[open] summary` rule changes the background color when a section is open. The `details p` rule adds padding to the content and a top border to separate it from the summary.

Step 3: Customizing the Appearance

You can further customize the appearance of your accordion using CSS. Here are some examples:

  • Icons: Add icons to the summary using the `::before` or `::after` pseudo-elements. You can use Unicode characters, font icons (like Font Awesome), or even SVG images.
  • Transitions: Add transitions to the opening and closing of the content for a smoother effect.
  • Colors and Typography: Adjust the colors, fonts, and other typography properties to match your website’s style.

Here’s an example of adding an arrow icon to the summary:


summary {
  position: relative; /* For positioning the arrow */
}

summary::before {
  content: "25B6"; /* Right-pointing triangle */
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 0.8em;
}

/* Rotate the arrow when the section is open */
details[open] summary::before {
  transform: translateY(-50%) rotate(90deg);
}

In this example, we use the Unicode character `25B6` for a right-pointing triangle. The `transform: rotate(90deg);` rotates the arrow to point downwards when the section is open, providing visual feedback to the user.

Step 4: Accessibility Considerations

Accessibility is crucial for web development. Ensure your accordions are accessible to all users, including those using screen readers or navigating with a keyboard.

  • Keyboard Navigation: The `details` and `summary` elements are natively keyboard-accessible. Users can navigate between the summary elements using the Tab key and open or close sections using the Enter or Spacebar keys.
  • ARIA Attributes: While the `details` and `summary` elements handle accessibility well, you can enhance accessibility by adding ARIA attributes. For example, you can add `aria-expanded=”true”` or `aria-expanded=”false”` to the `summary` element to indicate the open or closed state. However, this is often unnecessary as the browser handles this automatically.
  • Contrast: Ensure sufficient color contrast between the text, background, and icons to meet accessibility guidelines (WCAG).
  • Semantic Structure: Using semantic HTML elements like `details` and `summary` provides a good starting point for accessibility, allowing screen readers to easily understand the content’s structure.

Common Mistakes and How to Fix Them

Here are some common mistakes developers make when implementing accordions using `details` and `summary`, along with how to avoid them:

  • Forgetting the `summary` element: The `summary` element is essential. Without it, the `details` element will not have a visible control to open and close.
  • Incorrect CSS Styling: Applying CSS incorrectly can lead to visual issues. Make sure your CSS selectors are accurate and that you are using the correct properties to achieve the desired look. For example, use `list-style: none;` on the `summary` element to remove the default bullet points.
  • Over-complicating with JavaScript: Avoid using JavaScript for basic accordion functionality. The `details` and `summary` elements are designed to handle this natively. Only use JavaScript if you need advanced features.
  • Poor Accessibility: Neglecting accessibility considerations can exclude users. Always test your accordions with screen readers and keyboard navigation. Ensure sufficient color contrast.
  • Not Using Semantic HTML: Using incorrect HTML structure can make the accordion less accessible and less SEO-friendly. Always use the `details` and `summary` elements for their intended purpose.

Adding Advanced Features (Optional)

While the `details` and `summary` elements provide the core functionality, you might want to add advanced features using JavaScript. Here are a few examples:

  • Smooth Transitions: Use JavaScript to add smooth transitions when opening and closing the accordion sections. This can improve the user experience.
  • Persistent State: Store the open/closed state of the accordion sections in local storage so that the user’s preferences are remembered across page reloads.
  • Dynamic Content Loading: Load the content of an accordion section dynamically using AJAX when the section is opened.

Here’s a basic example of adding a smooth transition using JavaScript:


const detailsElements = document.querySelectorAll('details');

detailsElements.forEach(details => {
  details.addEventListener('toggle', () => {
    if (details.open) {
      details.style.transition = 'max-height 0.3s ease-in-out';
      details.style.maxHeight = details.scrollHeight + 'px';
    } else {
      details.style.transition = 'max-height 0.3s ease-in-out';
      details.style.maxHeight = '0px';
    }
  });
});

This script adds a `transition` to the `max-height` property when the `details` element is toggled. This creates a smooth animation effect. Note: This is just a starting point and may require additional styling and adjustments based on your specific needs.

SEO Considerations

Optimizing your accordions for search engines is important. Here are some SEO best practices:

  • Use Descriptive Titles: Write clear and concise titles for your `summary` elements. These titles should accurately reflect the content within each section and include relevant keywords.
  • Keyword Optimization: Naturally incorporate relevant keywords into your `summary` text and the content within the `details` elements. Avoid keyword stuffing.
  • Semantic HTML: Using the `details` and `summary` elements is inherently SEO-friendly because they provide semantic structure to your content.
  • Mobile-Friendliness: Ensure your accordions are responsive and work well on all devices. Mobile-friendliness is a significant ranking factor.
  • Content Quality: Provide high-quality, valuable content within your accordion sections. This will keep users engaged and encourage them to spend more time on your page, which is a positive signal for search engines.

Summary / Key Takeaways

  • The `details` and `summary` elements provide a simple, semantic, and accessible way to create accordions in HTML.
  • Use CSS to style your accordions and customize their appearance to match your website’s design.
  • Prioritize accessibility by ensuring your accordions are keyboard-navigable and meet WCAG guidelines.
  • Optimize your accordions for SEO by using descriptive titles, incorporating relevant keywords, and providing high-quality content.
  • Avoid unnecessary JavaScript for basic accordion functionality. Use it only for advanced features.

FAQ

Here are some frequently asked questions about building accordions with `details` and `summary`:

  1. Can I use JavaScript to enhance the functionality of accordions?

    Yes, you can use JavaScript to add features like smooth transitions, persistent state, and dynamic content loading. However, the basic functionality of opening and closing sections is handled natively by the `details` and `summary` elements, so it’s generally best to start with those.

  2. How do I style the arrow icon in the summary?

    You can style the arrow icon using CSS. Use the `::before` or `::after` pseudo-elements on the `summary` element. You can either use Unicode characters, font icons, or even SVG images for the arrow. Rotate the arrow using the `transform` property when the section is open to indicate the open/closed state.

  3. Are accordions accessible?

    Yes, the `details` and `summary` elements are natively keyboard-accessible. Users can navigate between the summary elements using the Tab key and open or close sections using the Enter or Spacebar keys. You can further enhance accessibility by adding ARIA attributes, though this is often not necessary.

  4. How do I make the accordion content responsive?

    Ensure that the content within the `details` element is responsive. Use relative units (percentages, `em`, `rem`), and media queries in your CSS to adjust the layout and styling for different screen sizes. Test your accordions on various devices and screen sizes to ensure they display correctly.

Mastering accordions with `details` and `summary` is a valuable skill in web development. By understanding the core concepts, following the step-by-step guide, and addressing common mistakes, you can create interactive and user-friendly interfaces. Remember to prioritize accessibility and SEO best practices to ensure your accordions are accessible to all users and rank well in search results. With practice and attention to detail, you can create dynamic and engaging web content that enhances the user experience and improves the overall performance of your web projects. The combination of semantic HTML, effective CSS styling, and careful consideration of accessibility and SEO creates a robust and user-friendly experience.