HTML `<details>` and `<summary>` Elements: Creating Collapsible Content Widgets

Learn how to use the HTML `<details>` and `<summary>` elements to create interactive collapsible content sections. This tutorial explains their purpose, usage, and how to customize their appearance using CSS, enhancing user experience by providing a clean and efficient way to show and hide additional information.



Using the HTML `<details>` and `<summary>` Elements

Understanding the `<details>` and `<summary>` Elements

The HTML `<details>` and `<summary>` elements create an interactive widget that allows users to show or hide additional information. The `<details>` element acts as a container for the content to be shown or hidden; the `<summary>` element provides a visible heading or label for the widget. The widget is closed by default; clicking the summary opens it, revealing the details. This enhances user experience by letting users control the display of additional information.

Using the `<details>` and `<summary>` Elements

The `<summary>` element must be the first child of the `<details>` element. Any content you want to be shown or hidden goes inside the `<details>` element. Here's an example:

Example: `<details>` and `<summary>`

<details>
  <summary>Epcot Center</summary>
  <p>Epcot is a theme park...</p>
</details>

Clicking "Epcot Center" will toggle the display of the paragraph.

Browser Support for `<details>` and `<summary>`

The `<details>` and `<summary>` elements are supported by most modern browsers. Here's a summary of browser compatibility.

Browser Version
Chrome 12.0
Edge 79.0
Firefox 49.0
Opera 6.0
Safari 15.0

Styling `<details>` and `<summary>` with CSS

You can customize the appearance of the `<details>` and `<summary>` elements using CSS. The example below shows how to add some basic styles:

Example: Styling with CSS

details {
  border: 1px solid #ccc;
  padding: 10px;
}

summary {
  font-weight: bold;
  cursor: pointer;
}

Global and Event Attributes

The `<details>` and `<summary>` elements support standard HTML global attributes and event attributes, providing flexibility in their behavior and interaction with the rest of the webpage.

The `open` attribute can also be added to the `<details>` tag to force the details to display when the page is loaded. For example: `<details open>`.