🛠 Simple CSS+JS dynamic max-height accordions!

⚠️ The problem with max-height accordions

I love the technique of using max-height to create accordions. Buuuuut , a big caveat is you can't transition between a max-height of 0 and auto . Leaving you to either:

  1. Use something like max-height: 999em to account for the tallest content length possible. This causes your opening and closing animations to be too quick.
  2. Use a smaller value for max-height , but what if your content is too large and it "cuts off" part of it?

💪 transitionend to the rescue!

You can add a transitionend eventListener to the accordion body (part that opens and closes) to dynamically calculate the max-height value! This event fires after a CSS transition completes. Meaning:

🎉 Demo

Example Heading

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aperiam tempora voluptatum eligendi rem molestias numquam totam dignissimos animi ullam a culpa modi soluta, vero quisquam vel similique quibusdam neque nam?

Ipsam dolorem ut similique ullam architecto eum corrupti dolor laboriosam neque error iure aliquam, inventore esse nemo, nisi laborum eaque, est officiis rem id. Doloremque velit excepturi eos tempore neque?

Pariatur eius harum, quidem cumque corporis ipsa odio quo at, fugit atque inventore sit accusamus dolor unde? Porro ab nihil maxime sunt quasi? Asperiores animi, consectetur provident a aspernatur totam.

Corrupti, voluptatem! Rem eveniet labore itaque velit amet vel sapiente qui harum quaerat aliquam veniam molestiae, corporis optio molestias magnam, nihil unde! Tempore voluptatem, quaerat sit neque repellat dignissimos earum?