Read the article below to learn how to create an accordion using Bootstrap 5.
How to create an accordion using Bootstrap 5
In the example below we are going to demonstrate how you can create an accordion using Bootstrap 5.
The first step in making an accordion is to make a parent div container and assign it an id. Here we have assigned it an id labeled “accordion”. The purpose of this parent div container is to hide all other collapsible elements when one of the collapsible elements are being shown.
For the sake of this example we will make use of the card component to generate an accordion. Therefore, in the above code, we are making a card by assigning it the .card class to a div container. Afterward, we are making the header of the card using the .card-header class and an anchor tag that hides/shows the content has been nested inside the header and connected to the collapsible div using the id.
Lastly, a div was made collapsible using the .collapse class and the card body was nested inside the collapsible container. Note that data-bs-parent=“#id” makes all other collapsibles to hide under the parent div container when one of the collapsibles is being displayed.
Another card was generated using the same technique as used for the first card. The only difference being that the id used to connect the anchor tag to the collapsible div is different from the one used for the first card.
Same approach was used to make yet another collapsible card having a different id that links the anchor tag with the collapsible div container.
An accordion was generated successfully.
Note: If you exclude data-bs-parent attribute then accordion items remain open while other items are opened.
Following the technique illustrated above you can easily generate an accordion using Bootstrap 5.
In order to make an accordion you have to make an element such as a div container collapsible using the .collapse class and nest such collapsible elements inside a parent element. The article above makes use of a card to generate an accordion. A total of three cards having a header and a body were generated and made collapsible. Each of the cards was linked to an anchor tag that was used to hide/show content placed inside each collapsible card. Moreover, the data-bs-parent=“#id” was used to hide all other collapsibles under the parent element while one is being displayed.