Sub topic 2
Disclosure Widgets with `details` and `summary`
This chapter assumes basic HTML structure, CSS selectors, and JavaScript event listeners. The earlier chapter introduced the required details and summary structure.
Content rules for the summary and hidden body
The summary element must be the first child of details. It provides the label users activate. The remaining content becomes the disclosure body.
<details>
<summary>What is your return policy?</summary>
<p>You can return items within 30 days of delivery.</p>
</details>The body remains in the document when the widget is closed, but the browser does not render it until the widget opens. Place complete, useful content inside it. Avoid putting another interactive control, such as a link or button, inside summary. Nested controls can make keyboard and screen-reader interaction confusing.
The open attribute controls the initial state:
<details open>
<summary>Shipping information</summary>
<p>Orders ship within two business days.</p>
</details>> callout note > Keep the summary short and descriptive. Users should understand what opens without reading the hidden body.
Styling the summary, marker, and open state
Use the details[open] selector to style the expanded state. The summary::marker pseudo-element targets the browser’s disclosure marker without removing its native behavior.
details {
border: 1px solid #ccc;
border-radius: 4px;
padding: 0.5rem 1rem;
}
summary {
cursor: pointer;
font-weight: 600;
}
details[open] summary {
margin-bottom: 0.5rem;
}
summary::marker {
color: royalblue;
}Do not hide the marker unless you provide another clear visual state. The marker helps users recognize that the summary is expandable.
Controlling the state from JavaScript
The open property reflects the attribute. Assign true or false to open or close the widget programmatically. The toggle event fires after its state changes.
<details id="faq">
<summary>How do I reset my password?</summary>
<p>Use the reset link on the sign-in page.</p>
</details>
<script>
const faq = document.querySelector("#faq");
faq.addEventListener("toggle", () => {
console.log(faq.open ? "expanded" : "collapsed");
});
faq.open = true;
</script>Use JavaScript when another part of the interface must respond to the disclosure state. For simple show-and-hide content, the native behavior is usually sufficient.
Exercise
Which selector styles a details element only while it is expanded?
Show answer
details[open].