Offcanvas navigation in Bootstrap 5

I found this code snippet in the official Bootstrap 5 demos, but I'm struggling to figure out how to transition the off-canvas menu from left-to-right. The documentation and demo codes are quite different.

As I work on a landing page in Bootstrap 5, my aim is to replace the default menu with an off-canvas menu featuring a close icon.

<!doctype html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/bootstrap.rtl.min.css">
    <title>Hello, world!</title>
</head>

... remaining HTML code as it is ...

The above HTML code showcases an example of implementing an off-canvas navbar utilizing Bootstrap's features. To shift the navbar from right to left, simply add .navmenu-fixed-left to the .navbar-offcanvas.

Answer №1

Utilizing inline styling, there is no need for additional CSS and JS to implement off-canvas features from left to right using Bootstrap itself. Check out the example below:

<!doctype html>
<html lang="zxx">

<head>
    <link rel="icon" type="image/png" href="img/favicon.png">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="J. Stulemeijer" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <title>Offcanvas Component Navbar Example · Bootstrap v5.2.0 Beta1</title>
    <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/starter-template/">    
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6b4b9b9a2a5a2a4b7a696e3f8e4f8e6fbb4b3a2b7e7">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
</head>

<body> 
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4 fixed-top" id="navbar">
        <div class="container-fluid">
            <a class="navbar-brand" href="index.html">Bootstrap 5</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbarExample-expand-lg" aria-controls="offcanvasNavbarExample-expand-lg">
                    <span class="navbar-toggler-icon" data-bs-target="#offcanvasNavbarExample-expand-lg"></span>
                </button>
            <div class="offcanvas offcanvas-start bg-dark" data-bs-hideresize="true" tabindex="-1" id="offcanvasNavbarExample-expand-lg" aria-labelledby="offcanvasNavbarExample-expand-lg">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title" id="offcanvasLabel" style="color:white;">Bootstrap 5</h5>
                    <button type="button" class="btn-close btn-close-white text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body bg-dark">
                    <ul class="navbar-nav justify-content-end flex-grow-1 pe-3">
                        <li class="nav-item">
                            <a class="nav-link active" aria-current="page" href="index.html">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="index.html">Link</a>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                    Dropdown
                            </a>
                            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                                <li><a class="dropdown-item" href="#">Action</a></li>
                                <li><a class="dropdown-item" href="#">Another action</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="#">Something else here</a></li>
                            </ul>
                        </li>                            
                        <li class="nav-item">
                            <a class="nav-link" href="#">Disabled</a>
                        </li>
                    </ul>
                    <form class="d-flex">
                        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
                        <button class="btn btn-outline-success" type="submit">Search</button>
                    </form>
                </div>
            </div>
        </div>
    </nav>
<div style="padding-top:5em">       
    <section class="container mb-4">
            <h2>Text to test body scrolling</h2>
            <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt...
            </p>
    </section>
</div>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f99b96968d8a8d8b9889b9ccd7cbd7c9d49b9c8d98c8">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>

</body>

</html>

Answer №2

I took a stab at identifying the origin of your example. It contains CSS specific to it and JavaScript tailored for it.

Here, I incorporated the CSS in the snippet CSS block and the JavaScript in that block

You may want to consider downloading from the example site instead of just copying. For what it's worth, I used the browser to examine the actual CSS source at play here.

(function () {
  'use strict'

  document.querySelector('#navbarSideCollapse').addEventListener('click', function () {
    document.querySelector('.offcanvas-collapse').classList.toggle('open')
  })
})()
html,
body {
  overflow-x: hidden; /* Prevent scroll on narrow devices */
}

body {
  padding-top: 56px;
}

@media (max-width: 991.98px) {
  .offcanvas-collapse {
    position: fixed;
    top: 56px; /* Height of navbar */
    bottom: 0;
    left: 100%;
    width: 100%;
    padding-right: 1rem;
    padding-left: 1rem;
    overflow-y: auto;
    visibility: hidden;
    background-color: #343a40;
    transition: transform .3s ease-in-out, visibility .3s ease-in-out;
  }
  .offcanvas-collapse.open {
    visibility: visible;
    transform: translateX(-100%);
  }
}

.nav-scroller {
  position: relative;
  z-index: 2;
  height: 2.75rem;
  overflow-y: hidden;
}

.nav-scroller .nav {
  display: flex;
  flex-wrap: nowrap;
  padding-bottom: 1rem;
  margin-top: -1px;
  overflow-x: auto;
  color: rgba(255, 255, 255, .75);
  text-align: center;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
}

.nav-underline .nav-link {
  padding-top: .75rem;
  padding-bottom: .75rem;
  font-size: .875rem;
  color: #6c757d;
}

.nav-underline .nav-link:hover {
  color: #007bff;
}

.nav-underline .active {
  font-weight: 500;
  color: #343a40;
}

.text-white-50 { color: rgba(255, 255, 255, .5); }

.bg-purple { background-color: #6f42c1; }
<!doctype html>
<html lang="fa" dir="rtl">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1f1212090e090f1c0d3d48534d534f">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <title>Hello, world!</title>
</head>

<body>
  <div class="container">
    <!-- Static navbar -->
    <nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark" aria-label="Main navigation">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">Offcanvas navbar</a>
        <button class="navbar-toggler p-0 border-0" type="button" id="navbarSideCollapse" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>

        <div class="navbar-collapse offcanvas-collapse" id="navbarsExampleDefault">
          <ul class="navbar-nav me-auto mb-2 mb-lg-0">
            <li class="nav-item">
              <a class="nav-link active" aria-current="page" href="#">Dashboard</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Notifications</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Profile</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Switch account</a>
            </li>
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-bs-toggle="dropdown" aria-expanded="false">Settings</a>
              <ul class="dropdown-menu" aria-labelledby="dropdown01">
                <li><a class="dropdown-item" href="#">Action</a></li>
                <li><a class="dropdown-item" href="#">Another action</a></li>
                <li><a class="dropdown-item" href="#">Something else here</a></li>
              </ul>
            </li>
          </ul>
          <form class="d-flex">
            <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-success" type="submit">Search</button>
          </form>
        </div>
      </div>
    </nav>
    <!-- Main component for a primary marketing message or call to action -->
    <div class="jumbotron">
      <h1>Offcanvas Navbar example</h1>
      <p>This example demonstrates using the offcanvas plugin with the navbar.</p>
    </div>
    <p>
      By default the navbar is show on the right side of the screen. You can show it on the left side instead by adding <code>.navmenu-fixed-left</code> to the <code>.navbar-offcanvas</code>.
    </p>
  </div>
  <!-- /container -->
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="53313c3c27202721322313667d637d61">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using Firefox to scale down a div with CSS `moz-transform`, the border details are unfortunately not retained

When viewing the following HTML in Firefox, you may notice that the right and bottom border is missing. However, Chrome and Internet Explorer display it correctly. Is this a bug in Firefox, or is there another method I can use to make it look consistent ...

Is there a way for me to achieve a vertical page turning effect on a single page?

I am seeking to develop a unique calendar display consisting of 12 images that give the illusion of flipping up when clicked. While I am aware of turn.js, my knowledge of javascript is limited and I need guidance on how to proceed. Despite having a program ...

dompdf: Setting a white margin on an A4 size paper

I'm currently utilizing dompdf, a PHP library, to generate PDF pages and I've encountered an issue with setting the correct dimensions. Whenever I apply the CSS property: @page { size: 21cm 29.7cm; } .... and let's say I want the top ...

Changing the height of SimpleBar in a component without using global styles in Angular

Is there a way to customize the height of my scrollbar without affecting other components? I tried using simplebar-scrollbar :: before in global style but it impacted other areas as well. I'm looking for a solution that only applies to my component. ...

Arranging images next to each other using CSS and HTML

I've been trying to arrange four images side by side, with two on the top row and two on the bottom. I want to ensure they stay consistent across all browser sizes except for mobile. Here is what I have attempted so far: #imageone{ position: absol ...

Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method wi ...

The navigation bar in responsive view on Bootstrap 4 causes the content below it to shift

Recently I have been exploring bootstrap-4 and encountered an issue while creating a nav-bar. The problem is that in responsive view, when toggling the nav-bar it simply pushes the content below it. Is there any way to address this issue within (bootstra ...

Steps for implementing a Toggle Navigation Bar in CSS

I'm looking to implement a show/hide navigation menu similar to the one showcased in this inspiration source: Code Snippet (HTML) <div id="menus"> <nav id="nav"> <ul> <li><a href="#">HOME</a></li> <li& ...

Blank area located at the bottom of the document

I'm having trouble designing a webpage without a scroll bar because there isn't much content to display on the page. I've tried searching for solutions and following steps to fix the issue, but I haven't had any success. If anyone can a ...

Error with displaying icon font within a box in Internet Explorer

Utilizing Wordpress with the UDesign theme has allowed me to incorporate iconfonts on my website within small blue boxes. You can view these icons in action on this page: To achieve this look, I had to customize the CSS by following an online tutorial tha ...

Having difficulty configuring particlesJS as the background

If you're looking to create a three-page single scrolling webpage with particlesJS as the background, consider using the following resources: particlesJS Website and particlesJS Github Page. An issue arises when trying to set particlesJS as the back ...

Verify whether the element within an iFrame contains any content

After conducting extensive research, I have been unable to find a satisfactory answer to my question. Therefore, I am reaching out to see if anyone has the knowledge I seek. The Goal: I aim to check the contents within an iFrame and determine whether it ...

Unable to trigger click events for marker connected to the end of the line

I need help with the following code. It includes a line with a marker attached to the end. I have written click events for both the line and the marker. However, the click event does not work when I click on the marker element, and the cursor properties ar ...

Do colors appear differently on various screens?

I've noticed that the background color #1ABC9B appears differently on various monitors when viewing my website. On MAC systems and smart phones, it appears as a lighter shade of green compared to other laptops where it appears darker. What could be ca ...

The CSS property object-fit: cover is unable to properly display JPEG images with EXIF orientation greater than 1

I'm having trouble with my Angular app and creating a gallery of photos from my Samsung Galaxy. I am using the "object-fit: cover" css attribute for a nice design, but it only seems to work correctly when the image has an EXIF "orientation" property e ...

How can we create and improve the visibility of the navigation for the UIKit slider

Is there a way to keep the navigation arrows of the Uikit slider always visible or add navigation circles below the slider? Your help is greatly appreciated. ...

Issue with excessive content causing scrolling difficulty

I've created CSS for a modal dialog, but I'm facing an issue. When the content exceeds the vertical space of the wrapper, the scrolling functionality doesn't work correctly. Although I can scroll, it's limited and I can't reach th ...

Utilizing flexbox for dynamic width adjustment with flex-grow functionality

Currently, I am in the process of configuring a menu bar using this particular template I have been attempting to achieve this layout utilizing FlexBox, but it appears that there is an issue. Here is the HTML code: <nav> <ul> < ...

What is the best way to create CSS that will only work on browsers other than IE and Edge?

I need assistance with writing CSS code that will only be applied to 'desktop' screen sizes when the page is viewed on browsers other than IE and Edge. Here's what I have so far: @media only screen and (min-width: 981px) /* and XXX */ The ...

Ways to incorporate a tertiary tier in my CSS dropdown navigation

I currently have a CSS code that displays a two-level menu, but I'm looking to expand it to include a third level. Unfortunately, I'm stuck and unsure of what changes to make in the CSS. Below is the existing code: #topnav{ // Existing CSS p ...