Andy from Webcrunch

Subscribe for email updates:

Portrait of Andy Leverenz
Andy Leverenz

November 21, 2020

Last updated November 5, 2023

How to use Details and Summary tags

If you've ever wanted an accordion-like user interface without all the fuss of custom JavaScript, CSS, and HTML look no further than the <detail> and <summary> tags in HTML5.

The HTML Details Element (<details>) creates a container element that is only visible when toggled into an "open" state. A summary can be optionally provided using the <summary> element.

When combined the <details> and <summary> elements give you a primitive toggle list of content with HTML alone. I like using this pattern for frequently asked questions, support documentation, or other documentation alone. It's very handy and fast to get started with.

For this tutorial, I made a custom CodePen to demonstrate how it works.

The typical markup looks like the following:

<details>
  <summary><strong>summary</strong> text</summary>
  Lorem ipsum dolor sit amet consectetur, adipisici......
</details>

The <details> tags surround both the content and the <summary> tags by design. The content within the <details> tags remains hidden minus the <summary> tags contents which acts as a toggle/control for expanding the hidden content.

Showing a <details> block by default

You can open a <details> element by default by passing open as an attribute.

<details open>
  <summary><strong>summary</strong> text</summary>
  Lorem ipsum dolor sit amet consectetur, adipisici......
</details>

Leveraging JavaScript with details and summary

On top of the built-in toggling effect, you can add additional styles using a "toggle" event listener built into the browser.

Here's a quick example of what you could achieve

const detailsElements = document.querySelectorAll('details')

detailsElements.forEach((detail) => {
  detail.addEventListener('toggle', () => {
    if (detail.open) {
      detail.style.borderColor = "red";
    } else {
      detail.style.borderColor = "#777777";
    }
  })
})

The code above scans the entire page for <details> elements. For every element that gets "toggled" we listen for that change and toggle the styles directly. In this case, I change the border color.

Be sure to check the final CodePen for a better example!

Link this article
Est. reading time: 2 minutes
Stats: 8,111 views

Collection

Part of the HTML & CSS collection

Products and courses