Collapsing Navbar Content
Sometimes we need to collapse the navbar to fit the content of the page on smaller screens, most commonly used for mobile devices by collapsing the navigation and displaying it through clicking on a hamburger menu.
For collapsing we need to set classes in two parts
- one are the classes for the element that is being collapsed in this case the navbar
- the second are the classes on the element that controls the collapse or the toggler.
Setting the collapsible content with the class of .collapse
, .navbar-collapse
and an id
attribute to link to the toggler.
<nav class="navbar bg-dark navbar-dark navbar-expand-md">
<a href="#" class="navbar-brand">Brigs and co.</a>
<div class="collapse navbar-collapse" id="togglerNav">
<ul class="navbar-nav">
<li class="nav-item"><a class=" nav-link" href="#">Home</a></li>
<li class="nav-item"><a class=" nav-link" href="#">About</a></li>
<li class="nav-item"><a class=" nav-link" href="#">Contact</a></li>
</ul>
</div>
</nav>
Setting the toggler with the class of .navbar-toggler
and .navbar-toggler-icon
to give us the styles for the toggler icon
We also need some additional settings to allow bootstrap to link the toggler with the collapsible navbar and aria roles for accessibility
data-toggle="collapse"
to use JavaScript for the collapse functiondata-target="#togglerNav"
to link with the id of the collapsible navbararia-controls="togglerNav"
to tell readers which content is being controlledaria-label="Toggle navigation"
to give a title for the button
<nav class="navbar bg-dark navbar-dark navbar-expand-md">
<a href="#" class="navbar-brand">Brigs and co.</a>
<button
class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#togglerNav"
aria-controls="togglerNav"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="togglerNav">
<ul class="navbar-nav">
<li class="nav-item"><a class=" nav-link" href="#">Home</a></li>
<li class="nav-item"><a class=" nav-link" href="#">About</a></li>
<li class="nav-item"><a class=" nav-link" href="#">Contact</a></li>
</ul>
</div>
</nav>