Create an Accordion using just HTML

Photo by River Fx on Unsplash

Create an Accordion using just HTML

Previously if you wanted to create an accordion element on your webpage you were forced to use JavaScript or jQuery. Now you can create a simple accordion using the <details> HTML tag. Let me show you how.

What is <details>

The <details> HTML element creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. A summary or label must be provided using the

element.

A disclosure widget is typically presented onscreen using a small triangle that rotates (or twists) to indicate open/closed status, with a label next to the triangle. The contents of the <summary> element are used as the label for the disclosure widget.

Accordion Demonstration

Here is the basic code necessary to create an accordion:

<details>
    <summary>Demo</summary>
    Hello World
</details>

Here is an animated Gif showing it working:

demo #1

Opening the Accordion

By default the content of the accordion is hidden. When a user clicks on it, then the content is displayed. You may want the default state of the accordion to be open. Add the open attribute to the <details> tag.

Here is an example:

<details open>
    <summary>Demo</summary>
    Hello World
</details>

This is what the accordion will look like by default:

open accordion

Using HTML to display content

In the previous example, I used straight text to display the accordion's content. You are not limited to displaying just text. You can also use HTML. Here is an example:

<details>
  <summary>Overview</summary>
  <ol>
    <li>Cash on hand: $500.00</li>
    <li>Current invoice: $75.30</li>
    <li>Due date: 5/6/19</li>
  </ol>
</details>

Here is an animated gif showing it working:

demo 2

Styling the Accordion

You can easily add styling to your accordion using the details and summary items. Here is an example:

details {
    border: 1px solid #aaa;
    border-radius: 4px;
    padding: .5em .5em 0;
}

summary {
    font-weight: bold;
    margin: -.5em -.5em 0;
    padding: .5em;
}

details[open] {
    padding: .5em;
}

details[open] summary {
    border-bottom: 1px solid #aaa;
    margin-bottom: .5em;
}

Here is what adding this styling does to our previous demo of an accordion with HTML content:

demo 3

Did you find this article valuable?

Support All Things Tech by becoming a sponsor. Any amount is appreciated!