Bootstrap Offcanvas
An offcanvas is a panel which slides in from the left, right, top or bottom of the screen. It is good for a mobile menu, a shopping cart, filters or a sidebar. It is new in Bootstrap 5.
A basic offcanvas
<button class="btn btn-primary" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasExample" aria-controls="offcanvasExample">
Open the offcanvas
</button>
<div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasExample" aria-labelledby="offcanvasExampleLabel">
<div class="offcanvas-header">
<h5 class="offcanvas-title" id="offcanvasExampleLabel">Menu</h5>
<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<div class="offcanvas-body">
<p>Some links or other content can go here.</p>
<ul class="list-unstyled">
<li><a href="#">Home</a></li>
<li><a href="#">Courses</a></li>
</ul>
</div>
</div>
Live preview
const oc = document.getElementById('offcanvasExample');
document.querySelector('[data-bs-toggle="offcanvas"]').click();
await new Promise(r => setTimeout(r, 700));
console.log('offcanvas open: ' + oc.classList.contains('show'));
console.log('placement class: ' + oc.className.split(' ').find(c => c.startsWith('offcanvas-') && c !== 'offcanvas-header'));
oc.querySelector('.btn-close').click();
await new Promise(r => setTimeout(r, 700));
console.log('offcanvas open after the close button: ' + oc.classList.contains('show'));
Console output (real Chrome)
offcanvas open: true
placement class: offcanvas-start
offcanvas open after the close button: false
Placement
| Class | Slides from |
|---|---|
.offcanvas-start | The left side (right side in RTL) |
.offcanvas-end | The right side |
.offcanvas-top | The top |
.offcanvas-bottom | The bottom |
Options
data-bs-backdrop="false"or"static"changes the dark layer behind the panel.data-bs-scroll="true"lets the page scroll while the offcanvas is open..offcanvas-lg(and others) makes the offcanvas a normal part of the page from a breakpoint. It is used in navbars for a mobile menu.
Use JavaScript
const panel = bootstrap.Offcanvas.getOrCreateInstance('#offcanvasExample');
panel.show();
panel.hide();
panel.toggle();
Offcanvas in a navbar
Replace the .collapse.navbar-collapse part of a navbar with .offcanvas.offcanvas-end. The menu is a normal row on big screens, and slides in on small ones.
Note:
Like a modal, an offcanvas traps the focus and closes with the Escape key. Give it a title and a close button. Next: Toasts.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |