Offcanvas Component

Bootstrap 5 doesn't really introduce a ton of new features, but one of the truly new features in recent version lets you build sidebars into your current project.


Trigger

  • button or A
    • data-bs-target
    • data-bs-toggle="offcanvas"

There are two parts of the Offcanvas container: the offcanvas trigger as well as the offcanvas content. Let's start with the trigger, which shows or hides the content.

The trigger can be either a button or an anchor tag. If you're using a link, you can simply add an href with the ID of the target, or you can a button an include a data-bs-target attribute with the ID or any CSS selector.

Although you can trigger these with JavaScript. Adding a data-bs-toggle with the value of offcanvas will initialize the component as well.


Offcanvas Container

  • offcanvas
    • show
    • offcanvas-POS
      • POS: start end top bottom
    • offcanvas-TYP
      • TYP: header title body
    • data-bs-scroll data-bs-backdrop

Try it

This is the thing that you want to show. The main container uses an offcanvas class.

The component will be hidden by default, but you can add the show class to have it show the component when the page is loaded.

You can control the position of the offcanvas with the offcanvas-POS class. The component will take the full width or height of one of the sides, so this lets you control where it appears.

There are some classes for the content inside, so you can have a header, title and body. It's also common to see a close button in the header that lets users close the component.

By default, when the component is showing, the background will have a dark overlay and not scroll, but you can control that with the data-bs-scroll and data-bs-backdrop attributes.

Notes:

  • offcanvas-POS: start, end, top, bottom
  • data-bs-scroll="true"
  • data-bs-backdrop="false"

Offcanvas Navbar

  • data-bs-toggle="offcanvas" in navbar-toggler
  • navbar-nav inside offcanvas-body

Try it

There is another option for the offcanvas component. You can use it inside a navbar component and it creates an interesting look for the navigation.

If you already have a navbar, the key is to change the data-bs-toggle property and change it from collapse to offcanvas. The button that usually toggles the navbar-collapse will point to the Offcanvas component instead.

You also need to add a tabindex="-1" to the offcanvas component and if you're using a header, which you really should so that it can have a close button, you should also have a aria-labelledby property with an ID of the header.

Other than that, the navbar-nav part of your navigation goes inside the offcanvas-body