Happy Friday! Here's a little article to end your week. It is a mirror of an article on my site. Feel free to visit it if you want to see live examples of what I show here!
Let's learn about <details />
<details />
is a very spiffy, yet relatively unadopted component in the HTML catalog. It's not super dynamic, but pretty useful if you ever want to build accordions like below:
Hacking with Details
The cool thing about <details />
is that it can act as a state machine in pure HTML. This means when we add some useful CSS selectors, we can make the <details />
element act like a full-fledged toggle button.
Let's look at this example below:
As you can see above, I just created a "button" entirely in CSS that increases the font-size of .open-me-target
on click of the summary.
Take note of the sibling combinator ~
and the attribute selector https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors. [open]
tell us to look at instances when the class .open-me has the attribute open, and (~
) tells us to look for instances when .open-me-target
follows .open-me
within the same parent element. This lets us only apply the blue, 50px style to instances that meet both of these criteria.
Polishing it up
While functional, the UI above looks kind of janky. Let's make it look a little better.
Pretty cool I think.
Notes
Other HTML elements can be used to create a toggle-like state, the most significant being <input type="checkbox" />
. I focused on <details />
because keyboard users can toggle using the return — which I find more natural — while checkboxes are toggled with the spacebar.
I probably wouldn't use this hack in production. Changing HTML components' core functionality, even if done carefully, hampers accessibility, as not all browsers can understand the wackiness we just wrote down.
Top comments (0)