The HTML <details>
and <summary>
elements provide a native way to create interactive disclosure widgets, often referred to as accordions. This allows users to show or hide additional content on a web page, improving user experience and content organization.
Example 1: Basic Disclosure Widget
<details>
<summary>Click to reveal more</summary> <p>This is the hidden content that appears when you click the summary.</p>
</details>
Explanation This code creates a simple expandable section. The text within <summary>
is always visible, and clicking it toggles the visibility of the content inside <details>
.
Example 2: Disclosure with Default Open State
<details open> <summary>Always Visible Title</summary>
<p>This content is visible by default when the page loads.</p>
</details>
Explanation By adding the open
attribute to the <details>
tag, the hidden content is displayed immediately when the page loads. Users can still toggle its visibility.
Example 3: Styling Disclosure with CSS
<style>
details {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
summary {
font-weight: bold;
cursor: pointer; /* Indicates the summary is clickable */
color: #007bff;
}
details[open] summary {
color: #dc3545; /* Change color when open */
}
</style>
<details>
<summary>Styled Disclosure Section</summary>
<p>You can use CSS to customize the appearance of your disclosure widgets for better web design.</p>
</details>
Explanation This example demonstrates applying CSS to enhance the visual appeal of the disclosure widget. You can style the border, padding, font, and even change colors based on the open
state.
Example 4: Multiple Disclosure Widgets
<details>
<summary>Section One</summary>
<p>Content for the first section.</p>
</details>
<details>
<summary>Section Two</summary>
<p>Content for the second section.</p>
</details>
<details>
<summary>Section Three</summary>
<p>Content for the third section.</p>
</details>
Explanation You can implement multiple independent disclosure widgets on a single page. This is perfect for FAQs or collapsible content sections, enhancing your website's organization.
Example 5: Disclosure with More Complex Content
<details>
<summary>Detailed Information</summary>
<h3>Subheading Here</h3>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<p>This section can hold any HTML content, including headings, lists, images, and more.</p>
</details>
Explanation The content within <details>
can be as complex as needed, including headings, lists, paragraphs, or even other HTML elements. This flexibility makes it ideal for organizing diverse content.