Pure HTML accordian.

Accordian is use to show and hide larger content on webpage to reduce scrolling. you might have encountered accordians on websites navigation menus and Q&A sections. Accordians allow user to have control over the content by expanding or collapsing it.

Here is what we will be building using only HTML and a little bit of CSS for basic styling.

HTML5 details and summary tag accordian

HTML5 details and summary tag allow us to create accordian without using any JavaScript.

Let's start, create index.html file with below content.

index.html
<html> <head> </head> <body> <div> <details> <summary>Accordian 1</summary> Something small enough to escape casual notice. </details> </div> </body> </html>

That's all HTML that we need for our accordian, easy, isn't it.

Now if you open index.html in your browser you should see a basic accordian with default style, if you like it then you can leave it here, it's an accordian.

HTML5 details tag creates a collapsable container, information in details tag is only visible when widget is toggle into an open state. summary tag is use to give a custom label or heading to collapsable container.

If you ommit summary in detail tag then browser will use a default label (usually 'Details').

Open Attribute

To keep accordian in open state, details tag accept a boolean open attribute.

<details open> <!-- By default the content will be shown --> </details>

Customized Styles

I would like to add some styles to it to make it look a little better. So, Create style.css in the same folder as index.html with below content and link it to index.html.

style.css
.container { background-color: ghostwhite; padding: 20px; width: 400px; margin: 100px auto; border-radius: 5px; } details { padding: 10px 5px 5px 5px; margin: 20px; } summary { font-weight: bold; margin: -5px -5px 0; padding: 5px; outline: none; } details[open] { // open state padding: 5px; border: 1px solid #ccc; background-color: white; border-radius: 5px; } details[open] summary { border-bottom: 1px solid #aaa; margin-bottom: 10px; }

Events

Apart from usual events supported by HTML elements, details tag supports toggle event. toggle event is fired on details tag whenever its state changes between open to close. Event is fired after state has toggled.

From MDN

If the state changes multiple times before the browser can dispatch the event, the events are coalesced so that only one is sent.

let details = document.getElementsByTagName("details")[0]; details.addEventListener("toggle", function (event) { console.log(event.target.open); });

Conclusion

I hope you learned something new, HTML5 browser support is very limited so make sure your targeting browser supports details and summary tag. To know more about browser support click here.

Codepen Link Here .

Say Hi on twitter and email

Designed and developed by Gulam Hussain.

Built with Gatsby. Hosted on Netlify.