HTML <summary> Tag
The HTML <summary> tag is used to create a visible heading for the <details> element. The <details> element is used to display collapsible content, and the <summary> tag provides a clickable label that toggles the visibility of the content.
By default, the <summary> text is visible, and clicking on it expands or collapses the hidden content within the <details> element.
Basic Syntax of HTML <summary> Tag
The <summary> tag must be nested inside a <details> element. Its basic structure is:
<details>
<summary>Summary Text</summary>
Hidden content goes here.
</details>
Clicking on the <summary> text toggles the visibility of the content inside the <details> tag.
Example of Using the <summary> Tag
Here’s an example of using the <summary> tag to create collapsible FAQ content:
index.html
<!DOCTYPE html>
<html>
<body>
<h2>Frequently Asked Questions</h2>
<details>
<summary>What is HTML?</summary>
HTML (HyperText Markup Language) is the standard language for creating webpages.
</details>
<details>
<summary>What is the <summary> tag?</summary>
The <summary> tag is used to provide a clickable label for the <details> element.
</details>
</body>
</html>
Explanation: Clicking on the question in each <summary> tag expands or collapses the answer inside the corresponding <details> element.
Styling the <summary> Tag with CSS
You can customize the appearance of the <summary> tag using CSS:
index.html
<!DOCTYPE html>
<html>
<head>
<style>
summary {
cursor: pointer;
font-size: 18px;
font-weight: bold;
color: #007BFF;
}
details[open] summary {
color: #FF5722;
}
</style>
</head>
<body>
<h2>Styled Summary Example</h2>
<details>
<summary>Click to reveal content</summary>
This is the hidden content that becomes visible when you click the summary.
</details>
</body>
</html>
Result: The summary text changes color when the <details> element is expanded, providing visual feedback to the user.
Attributes of HTML <summary> Tag
- Global Attributes: The
<summary>tag supports all global attributes, such asid,class, andstyle. - Event Attributes: You can attach event handlers like
onclick,onmouseover, etc., to the<summary>tag.
These attributes make it possible to style and interact with the <summary> element dynamically.
Practical Applications of the <summary> Tag
- FAQs: Use the
<summary>tag to create expandable questions with hidden answers. - Collapsible Sections: Organize long documents or articles into sections that can be expanded or collapsed.
- Interactive Guides: Provide step-by-step instructions with collapsible steps for better user experience.
- Menus: Build collapsible navigation menus with the
<details>and<summary>elements.
The <summary> tag, when used with the <details> element, creates accessible, user-friendly, and interactive content for webpages.
