Hide details until needed
2 minute read
The <details> element (also known as the disclosure element) hides content until a user chooses to view it. You can use this element to reduce the visual impact of large content blocks, such as extended source code, detailed configuration files, videos, and so on.
By default, <details> hides content until the user chooses to view it.
The <details> element is a core HTML element supported by many modern browsers.
Example
Here’s an example of the <details> element:
Expand to view an image
The Pale Blue Dot - Revisited (2020)
This is an updated version of the Pale Blue Dot, a photo taken by Voyager 1 near the planet Saturn on Valentine’s Day 1990.
In the words of astronomer Carl Sagan, this image shows our home. “That’s us… [T]he pale blue dot, the only home we’ve ever known.”
Photo credit: The Pale Blue Dot (2020 variant), copied from NASA’s Astronomy Picture of the Day (APOD), 14 Feb 2020 entry. Credits: Voyager Project, NASA, and JPL-Caltech.
Here, the <details> element hides a large image. When you display the image, the rest of the content is pushed down the page.
Users unfamiliar with your site may not realize the additional content exists. By hiding content by default, you allow the user to choose when to view it.
For best results, design web experiences to support users who engage content in different ways.
Source
The code underlying the example is:
<details>
<summary>Expand to view an important image</summary>
<p><em>The Pale Blue Dot - Revisited (2020)</em></p>
<img src="/images/astro/pale-blue-dot-2020.jpeg" alt="...">
<!-- details removed for brevity -->
</details>
CSS improvements
You can use traditional CSS techniques to improve the experience, as shown here:
details {
border:1px solid #fafafc;
border-radius:4px;
padding:.5em .5em 0
}
summary {
font-style:italic;
background-color:#f5f5f5;
margin:-.5em -.5em 0;
padding:.5em
}
.details>summary::before {
font-style:normal;
content:"\1F3A6 "
}
details[open] {
padding:.5em
}
details:hover {
border:1px solid #ddd;
box-shadow:#ccc 1px 1px 1px
}
An interactive demo shows these properties in action.
Vital statistics
- 4 Jun 2024: Minor edits to improve readability and article focus.
- 23 May 2024: First post