html: a second look at details

2020-11-13

 | 

~2 min read

 | 

391 words

On some pages, it may make sense to have some details hidden by default but present should a reader want additional information. That’s what Julian Shapiro does on his website and I love it (I have even written about it previously)! At the time, I mentioned at that time, there was a lot more to investigate.

I have had a little more time to play around and found it really pleasant to use (with one exception which had more to do with how Ember renders components than anything else). I pulled together a quick example in a Code Sandbox to demonstrate how it works and illustrated some animation use cases.

The App.tsx is very bare-bones:

App.tsx
export default function App() {
  return (
    <div className="App">
      <details>
        <summary>
          <div className="summaryWrapper">
            Hello CodeSandbox
            <FontAwesomeIcon icon={faChevronDown} className="icon" />
          </div>
        </summary>
        <p>Start editing to see some magic happen!</p>
        <p>It will sweep you off your feet!</p>
      </details>
    </div>
  )
}

Meanwhile, the CSS in styles.css is not much more complicated:

styles.css
.detailsReset > summary {
  list-style: none;
}

.detailsReset > summary::before {
  display: none;
}

.detailsReset > summary::-webkit-details-marker {
  display: none;
}

.summaryWrapper {
  display: flex;
  justify-content: space-between;
}

.icon {
  transition: transform 0.5s;
}

details[open] .icon {
  transform: rotate(180deg);
}

details[open] summary ~ * {
  animation: sweep 0.5s ease-in-out;
}

@keyframes sweep {
  0% {
    opacity: 0;
    margin-left: -50px;
  }
  100% {
    opacity: 1;
    margin-left: 0px;
  }
}

Some notes:

  • You may notice there’s no click handler. By default, the <details> element manages its state through an open property which is toggled on a toggle event.1
  • I wanted to have a custom icon to demonstrate the animation and reached for Font Awesome out of habit.
  • I wrapped the contents of the <summary> in a <div> because of a bug in Safari where the <details> element cannot act as flex containers.

Want to learn more?

There are a bunch of great resources out there about <details>. Some that I’ve found useful:

Footnotes


Related Posts
  • HTML: Styling Details


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!