How to Build an Accordion Menu Using HTML, CSS and JavaScript

Just finished this great tutorial. I had one question though. This is the css to open the div:

/* Unhides the content part when active. Sets the height */

.accordion .container.active .content {
  height: 150px;
}

I’m wondering if there is a reason that the height was set to a fixed 150px. In the example this works because all of the content is about the same size. However if I make one smaller there is a big empty gap when it is opened.

I changed this to height: 100% and it seems to work just fine.

Is there a good reason to have it at a fixed height?

Probably not. Using a fixed height, especially in px is usually not a great idea, but we’d need to see the actual implementation to really judge it. Do you have a link to your menu that we can look at?

P.S. I don’t mean to be too critical of this tutorial but it doesn’t address any of the accessibility issues with accordions. I’d suggest you take a look at some articles that include accessibility enhancements. A really good one is:

My favourite accessible accordion pattern

And the W3C provides an example of what they consider to meet all the accessibility guidelines:

WAI-ARIA Authoring Practices - Accordion Example

I don’t have mine on the web, but here is a codepen from the creator: https://codepen.io/ubahthebuilder/pen/gORqxNe

Thanks for the link. Ya, I don’t think you need to specify a height at all on these divs as they will grow as tall as needed to contain their content. Now perhaps the author wanted them to all be the same height so that it looks nice and uniform if they are all expanded? There are ways to do that but using px is not one of them.

1 Like

Oh, I think I just figured out why the fixed height. If you put the height to auto, then the transition doesn’t work.

Wonder if there are workarounds.