lewis4u lewis4u - 6 months ago 85
HTML Question

Bootstrap navbar with collapsed menu icon - How to?

On this bootstrap starter template:

enter image description here

when the browser gets narrow the navigation bar links/buttons collapse into one icon in top-right corner like this:

enter image description here

I would like to have this collapsed "icon" as default like on the picture above. So that the navbar links are available after the user clicks that top-right collapsed button.

How to do that?

This is the source code of the template:

<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>

<div class="container">

<div class="starter-template">
<h1>Bootstrap starter template</h1>
<p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
</div>

</div><!-- /.container -->

Answer

It's all in the CSS.

See this post and check out the css column.

Always Collapse Bootstrap Nav

Working Example:

.navbar .navbar-header {
  float: none;
}
.navbar .navbar-toggle {
  display: block;
}
.navbar .navbar-collapse.collapse {
  display: none!important;
}
.navbar .navbar-nav {
  float: none!important;
}
.navbar .navbar-nav > li {
  float: none;
}
.navbar .navbar-collapse.collapse.in {
  display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-inverse navbar-static-top">

  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <div class="navbar-collapse collapse" id="navbar">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a>
      </li>
      <li><a href="#about">About</a>
      </li>
      <li><a href="#contact">Contact</a>
      </li>
    </ul>
  </div>

</nav>