Headings that Expand and Collapse

Start with content that has a heading, e.g.

<h2>Section Title</h2>

<p>Section text here</p>
<p>More text here</p>

To make the section collapsible, it needs to be wrapped in div tags like this:

<div>
<p>Section text here</p>
<p>More text here</p>
</div>

After you've put the content in a div, give that div the class name collapse and a unique ID:

<div class="collapse" id="uniqueID">
<p>Section text here</p>
<p>More text here</p>
</div>

Now turn your section title into a link with the following code:

<h2><a href="#uniqueName" class="collapsed" data-toggle="collapse">Section Title</a></h2>

Note that href has to equal the unique ID of the div. This is so the link, when clicked, knows which div it's supposed to expand or collapse. So if you want multiple divs on the page that can be expanded or collapsed, each one must have a unique ID.

Note: If you want a section to be expanded by default when a page loads instead of hidden/collapsed, rewrite the link heading code as follows:

That is, remove the code class=collapsed (when you include class=collapsed, it makes the link show up with a "Plus" icon to indicate the content can be expanded. This "Plus" icon changes to a "Minus" when the content is expanded). You also need to change the section's div code from:

to:

Markup for complete, working example:

If you'd like to add a button that toggles multiple sections at the same time, you need to add one more class to each div. For this example, we'll call the class collapse-all though you can use whatever name you prefer:

The code for the button would look like this:

For aria-controls, list all the div IDs you want the button to control. For data-target, use the class collapse-all (or whatever name you chose - it just needs to be the same for each div). So the complete code would look something like this:

Last updated

Was this helpful?