Quick Tip: How to Customize Bootstrap 4’s Accordion Component
Note: This tutorial assumes you have some familiarity with Bootstrap 4.
1. Include Font Awesome Icons
2. Build a Simple Accordion
To create our accordion we’ll rely on some example code for the accordion component, kindly provided by Bootstrap.
Our accordion will contain three collapsible elements:
In our example all collapsible elements are closed to begin with.
But let’s say that we want the first collapsible element to be opened by default. To do so we have to add the show class to it, then on the related button (control) element we remove the collapsed class, and, for accessibility, set aria-expanded="true".
Here’s our accordion with that change made:
Multiple Collapsible Elements Opened
Sometimes we might want to have multiple collapsible elements open at the same time. We can achieve this by removing the data-parent attribute from all collapsible elements.
Here’s a demo with that behavior:
Animating The Position
Consider the following scenario: imagine there’s a lot of content inside the collapsible elements. At a certain point you read the text inside the second element, after which you click to see the contents of the third collapsible item. The second item closes again, so now, in order to see the beginning of the third element, you’ll have to scroll back up. Ugh, not great UX.
Here’s what it looks like:
One simple fix, which takes advantage of the shown.bs.collapse event, is to fire a scroll animation to the top position of the associated control.
In this short tutorial we played with Bootstrap 4’s accordion component, covered some common requirements, and built some solutions. You can now go and apply the knowledge gained today in your upcoming Bootstrap projects.
If you’ve ever built any other useful extensions for Bootstrap’s accordion component, let us know in the comments below.