Bootstrap 5 Collapse
Bootstrap 5 Collapse can easily show and hide content.
data-bs-toggleanddata-bs-targetThese are custom data attributes used to define component behavior and target elements.
1. data-bs-toggle attribute:
- Used to define the behavior of the component, indicating when the component is triggered.
- The settable values depend on the specific component type, such as
"collapse"(collapse menu),"modal"(modal),"tab"(tabs), etc. data-bs-toggle="collapse"Used to trigger the expansion and collapse of the collapse menu.data-bs-toggle="modal"Used to trigger the showing and hiding of the modal.data-bs-toggle="tab"Used to trigger the switching of tabs.
2. data-bs-target attribute:
- Used to specify the target element or target selector of the component.
- The target element can be a CSS selector, used to identify the specific element to be operated on.
- It can also be a specified element ID, starting with
#such asdata-bs-target="#myModal"。 data-bs-targetThe attribute anddata-bs-toggleattribute are used together to associate the component behavior with the target element.
In the following example, when the button is clicked, the data-bs-toggle="collapse" attribute triggers the collapse menu behavior, and the data-bs-target="#demo" attribute specifies that the target element of the collapse menu is the <div> element with ID demo.
Example
Try it Yourself »
Example Explanation
.collapseThe class is used to specify a collapsible element (the <div> in the example); after clicking the button, it will toggle between hidden and shown.
To control the hiding and showing of content, you need to add thedata-bs-toggle="collapse"attribute.data-target="#id"The attribute corresponds to the collapsible content (<div id="demo">).
Note:On an <a> element, you can use thehrefattribute instead of thedata-bs-targetattribute:
Example
Try it Yourself »
By default, the collapsible content is hidden. You can add the.showclass to make the content shown by default:
The following example extends the card component to display a simple accordion.
Note:Use thedata-bs-parentattribute to ensure all collapsible elements are under the specified parent element, so that when one collapsible option is shown, the other options are hidden.
Example
Try it Yourself »