The Details toggle component is what we used to use for most toggle-able content today.
- It's simple and well understood.
- Because it's CSS-based, there's no flash of unstyled content: what should be invisible is, and vice-versa.
- The class names
Details-content--shown
andDetails-content--hidden
can be confusing. (If you thought that "shown" was shown when the details are "on", you were wrong just like me!)
- Details components can't be nested. Because it's CSS-based, the outermost
.Details--on
state always "wins", and there's no workaround without some really ugly hacks.
The <details>
HTML element has native expand/collapse capabilities in modern browsers, and can be reliably polyfilled in older ones. By default, all direct descendents (elements and text nodes) of <details>
are hidden unless it has the open
attribute, and except the <summary>
element.
Live example:
Click here for more
This isn't visible until you click the text above, and will disappear when you click it again.
And the markup:
<details>
<summary>Click here for more</summary>
<p>This isn't visible until you click the text above, and will disappear when you click it again.</p>
</details>
- Progressive enhancement: Browsers that don't support it natively (and even with JS disabled!) will just show all the content by default.
- Can be targeted with CSS in different states with the
open
attribute. - Can be nested!
- Requires some normalizing CSS to remove the expand/collapse triangle icon.
- Can't target anything other than the direct descendent flow content for showing and hiding. In other words, the entire
<summary>
is visible all the time, so it's not possible to mimic theDetails-content--shown
andDetails-content--hidden
behavior.
Mu-An has been steadily porting over some Details component implementations to use <details>
instead, and it's going well.
The other day, @katmeister inquired about nested Details components in Slack. She needed them to make the new comment minimization feature work, because there were a couple of contexts in which minimized comments needed to live within other toggle-able sections:
- In the PR files view, you can expand and collapse individual files, and the minimized code comments are nested within those.
- In the PR discussion view, minimized comments can appear in outdated chunks.
Kat and I bounced around lots of different potential solutions:
- Hack the CSS. This was awful.
- Add the ability to nest the Details component in JS. Not compatible with the CSS.
- Add a new JS behavior for a new class on
<details>
elements. This was the winner!
For more context, see Mu-An's original web-systems issue and my design-systems discussion.