How to close Bootstrap open collapse navbar clicking outside of navbar elements [Best method]

/ January 9, 2021 / Bootstrap, CSS
How to close bootstrap open collapse navbar by clicking outside navbar

You might be trying to relocate the navbar to the right or left side of the layout. For left and right sidebar or navbars closing them by clicking outside is a good functionality.

Javascript Method (Personally I don’t do this)

$(document).ready(function () { 
  $(document).click(function () {
     // if($(".navbar-collapse").hasClass("in")){
       $('.navbar-collapse').collapse('hide');
     // }
  });
});

CSS Method

You will need 1 line of html code and few lines of CSS.

HTML

<!--   Add this line above navbar   -->
<a class="close-navbar-toggler collapsed" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
</a>

CSS

.navbar{
/*   z-index should be above .close-navbar-toggler */
  z-index:2;
}
.close-navbar-toggler{
  position:absolute;
  top:0;
  left:0;
  height:100%;
  width:100%;
  z-index:1;
  cursor:pointer;
}
.close-navbar-toggler.collapsed{
  z-index:-1;
}

View the Codepen to understand better

See the Pen Close Bootstrap open collapse navbar clicking outside of navbar by KiranWorkspace (@kiranworkspace) on CodePen.


Related Post

How to make Ellipsis to multiline text in CSS
Showing 1 or 2 lines of the title looks good on designs like card or excerpt, also important to handle…

CSS, Front-End / December 31, 2020

How to center a div vertically or horizontally or both
Center a div! Don't worry, it will never be a difficult CSS anymore! Most of the beginners do fail to…

CSS, Front-End / August 31, 2020