Accordion – <Details> and <Summary>
The <details>
and <summary>
tags are used to create an accordion element that can be dynamically opened and closed. These tags are unique as they can add dynamic visual effects even without CSS and JavaScript. These tags are often used to hide detailed information to simplify website design at a glance.
Syntax
The <summary>
element should be nested under the <details>
element. After the <summary>
element, you can describe what you want to show when the box is open. Here is an example of an implementation of the <detail>
and <summary>
elements.
<details>
<summary>Weather in London: Sunny</summary>
<ul>
<li>20 °C</li>
<li>Humidity: 43%</li>
<li>Wind: 2 m/s</li>
</ul>
</details>
You'll see the output below.
Weather in London: Sunny
- 20 °C
- Humidity: 43%
- Wind: 2 m/s
Attribute
You can use the open
attribute if you want to open the box when a browser loads the page.
Practice
Objective:
Create an accordionCreate an accordion with the open status
1. Create a new HTML file for this chapter
- Create a new file chapter7.html under the html-css-introduction directory.
- Type
!
and hit tab or enter to create an html template. - Change the
<title>
section to 7. Bridging HTML and CSS.
2. Add new code in the body section of the HTML document
In the <body>
section, type (copy & paste) the following code:
<h1>Chapter 7. Bridging HTML and CSS</h1>
<h2>Details and Summary</h2>
<details open>
<summary>Weather in London: Sunny</summary>
<ul>
<li>20 °C</li>
<li>Humidity: 43%</li>
<li>Wind: 2 m/s</li>
</ul>
</details>
<details open>
<summary>Weather in New York: Cloudy</summary>
<ul>
<li>17 °C</li>
<li>Humidity: 47%</li>
<li>Wind: 2 m/s</li>
</ul>
</details>
After editing the file, make sure that you save it (⌘ + S for Mac, Ctrl + S for Windows).
2. Check the result with a browser
- Open chapter7.html with a browser
- You'll see an accordion like in the video below
You can also check the sample result here (Demo Site).