Fun with <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:

<details>
    <summary>Open me!</summary>
    ![alt text](https://sfo2.digitaloceanspaces.com/shub/docs/web-tips/fun-with-details/doge.png)    
</details>

Open me! alt text

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:

<style>
    .open-me-target {
        font-size: 18px;
    }

    .open-me-target {
            width: 25px;
            height: 25px;
            background-color: red;
            border-radius: 50%;
        }

    .open-me[open] ~ .open-me-target {
        width: 50px;
        height: 50px;
        background-color: blue;
    }
</style>
<details class="open-me">
    <summary>Click Me!</summary>
</details>
<div class="open-me-target"></div>

Click Me!

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 [open]. [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.

<style>
    .open-me-1 {
        width: 150px;

    }

    .open-me-1 > summary {
        list-style: none;
        background-color: #cedfff;
        border-radius: 5px;
        text-align: center;
        padding: 5px;
        font-weight: 600;
        border: 1px solid #aecaff;
    }

    .open-me-1 > summary::-webkit-details-marker {
        display: none;
    }

    .open-me-1-target {
        width: 25px;
        height: 25px;
        background-color: red;
        border-radius: 50%;
    }

    .open-me-1[open] ~ .open-me-1-target {
        width: 50px;
        height: 50px;
        background-color: blue;
    }
</style>
<details class="open-me-1">
   <summary>Click Me!</summary>
</details>
<div class="open-me-1-target"></div>

Click Me!

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.