This article will provide a detailed guide on:
How to Create Offcanvas Sidebar
To create an offcanvas sidebar, add .offcanvas class in a div tag with its position of revealing .offcanvas-start and a unique id. Afterwards, wrap this div around a div with the class .offcanvas-header which contains the sidebar title with its dismissal button and a div with the class .offcanvas-body which contains the content of the sidebar.
Lastly, to trigger the offcanvas sidebar use data-bs-toggle=”offcanvas” and data-bs-target=”#id” to connect the sidebar with a button or a link which on clicking reveals the offcanvas sidebar:
Code
<div class="offcanvas-header">
<h1 class="offcanvas-title">Menu</h1>
<button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
</div>
<div class="offcanvas-body">
<div class="row">
<div class="list-group">
<a class="list-group-item list-group-item-action active" href="#">Home</a>
<a class="list-group-item list-group-item-action" href="#">About</a>
<a class="list-group-item list-group-item-action" href="#">Product</a>
<a class="list-group-item list-group-item-action" href="#">Contact Us</a>
<a class="list-group-item list-group-item-action" href="#">Settings</a>
</div>
</div>
</div>
</div>
<div class="container mt-3">
<h3>Offcanvas Sidebar</h3>
<p>Button Below Will Open Offcanvas Sidebar.</p>
<button class="btn btn-primary" type="button" data-bs-toggle="offcanvas" data-bs-target="#oc">
Open
</button>
</div>
This is how you create an offcanvas sidebar in bootstrap 5.
Offcanvas Positions
Offcanvas sidebar can be revealed from any edge of the screen as per user requirement. To specify the offcanvas position, just add .offcanvas-start/end/top/bottom class with .offcanvas class.
Start
.offcanvas-start class will reveal the sidebar from the left side of the page.
End
.offcanvas-end class will reveal the sidebar from the right side of the page.
Top
.offcanvas-top class will reveal the sidebar from the top side of the page.
Bottom
.offcanvas-bottom class will reveal the sidebar from the bottom side of the page.
Conclusion
Offcanvas sidebar is created by adding .offcanvas class to a div. Then add .offcanvas-start/end/top/bottom to specify the sidebar position and id attribute to give the sidebar a unique id. Afterwards wrap this div around a div with the class .offcanvas-header which contains the sidebar title with its dismissal button and a div with the class .offcanvas-body which contains the content of the sidebar. Now to trigger the offcanvas sidebar use data-bs-toggle=”offcanvas” and data-bs-target=”#id” to connect the sidebar with a button or a link which on clicking reveals the offcanvas sidebar.