In Bootstrap 5, the Offcanvas component is used to create an off-canvas sidebar or menu that can slide in from the left or right side of the screen. It is commonly used for navigation menus, sidebars, or content panels that can be hidden and revealed on demand. Here’s how you can use the Offcanvas component in Bootstrap 5:
- Set up the HTML structure for the offcanvas:
<!-- Add a button to trigger the offcanvas -->
<button class="btn btn-primary" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasExample" aria-controls="offcanvasExample">
Open Offcanvas
</button>
<!-- Define the offcanvas container -->
<div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasExample" aria-labelledby="offcanvasExampleLabel">
<div class="offcanvas-header">
<h5 class="offcanvas-title" id="offcanvasExampleLabel">Offcanvas Title</h5>
<button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<div class="offcanvas-body">
<!-- Offcanvas content goes here -->
<p>This is the offcanvas content.</p>
</div>
</div>
In this example, a button is added to trigger the offcanvas. It has the data-bs-toggle="offcanvas"
attribute, which indicates that it should activate the offcanvas behavior. The data-bs-target
attribute is set to the ID of the offcanvas container (#offcanvasExample
), and the aria-controls
attribute references the ID of the offcanvas for accessibility purposes.
The offcanvas container is defined using a <div>
element with the offcanvas
class. The offcanvas-start
class specifies that the offcanvas should slide in from the left side of the screen. If you want it to slide in from the right side, you can use the offcanvas-end
class instead.
Inside the offcanvas container, you can customize the header and body sections according to your needs. The header section contains a title and a close button, while the body section holds the content of the offcanvas.
To close the offcanvas, you can either click the close button in the header or use the data-bs-dismiss="offcanvas"
attribute on a button or link inside the offcanvas.
You can further customize the Offcanvas component by adding additional options, such as different sizes, animations, or backdrop behavior.
Feel free to use the Offcanvas component to create a sliding sidebar or menu in your Bootstrap 5 project. For more details and additional options related to the Offcanvas component, refer to the official Bootstrap documentation.