Collapsing Sidebar with Bootstrap

Chris We picture Chris We · Oct 16, 2013 · Viewed 472.5k times · Source

I just visited this page http://www.elmastudio.de/ and wondered if it is possible to build the left sidebar collapse with Bootstrap 3.

Code to collapse the sidebar from the top (phone only):

<button type="button" class="navbar-toggle sidebar-toggle" data-toggle="collapse" data-target=".sidebar-ex1-collapse">
    <span class="sr-only">Sidebar</span>
    <span class="glyphicon glyphicon-check"></span>
</button>

Sidebar itself has the hidden-xs class. It is removed with the following js

$('.sidebar-toggle').click(function(){
     $('#sidebar').removeClass('hidden-xs');            
});

If you click the button it toggles the sidebar from the top. It be great to see the sidebar behave like the website above shows. Any help is appreciated!

Answer

Zim picture Zim · Oct 16, 2013

Bootstrap 3

Yes, it's possible. This "off-canvas" example should help to get you started.

https://codeply.com/p/esYgHWB2zJ

Basically you need to wrap the layout in an outer div, and use media queries to toggle the layout on smaller screens.

/* collapsed sidebar styles */
@media screen and (max-width: 767px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
  }
  .row-offcanvas-right
  .sidebar-offcanvas {
    right: -41.6%;
  }

  .row-offcanvas-left
  .sidebar-offcanvas {
    left: -41.6%;
  }
  .row-offcanvas-right.active {
    right: 41.6%;
  }
  .row-offcanvas-left.active {
    left: 41.6%;
  }
  .sidebar-offcanvas {
    position: absolute;
    top: 0;
    width: 41.6%;
  }
  #sidebar {
    padding-top:0;
  }
}

Also, there are several more Bootstrap sidebar examples here


Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?