Collapsible Navigation Bar – A Must for Mobile Friendly

After you learn how to build a basic bootstrap navigation bar, you will want to know how to transform it to a collapsible navigation bar. Why? Well, if the user is on a small mobile device, then the navigation bar may consume the entire screen. This would result in a bad user experience, and the user may quickly leave your site. If you build a collapsible navigation bar, then the user experience is improved.

In order to build a collapsible navigation bar, you will need to program your site so it knows what to display when the nav bar is collapsed, and when it is not collapsed.

Start with your basic nav bar code from the previous lesson, and build on it to add the code necessary to build a collapsible navigation bar.

The correct code is shown below. Directly below are descriptions of all the additions shown in the code.

Collapsible Nav Bar Code
HTML5 Code for a Collapsible Navigation Bar

An Analysis of the Collapsible Navigation Bar Code

Make another <div> element for the collapsed navbar. Label it with comments, so you can distinguish the nav bars.

Add the built-in bootstrap class “navbar-header” to the collapsed navbar. This class tells your page that the collapsed navbar should sit on top of everything else.

Add the “collapse navbar-collapse” class to your un-collapsed ‘div’ element.

The next step is to make a make the <button> in your collapsed ‘div’ interact with your un-collapsed <div>. So, set a “main_navbar” id inside your un-collapsed <div>.

Now you will add a whole slew of characteristics to your button. Look above at all the characteristics added to the <button> tag. The type given improves accessibility. The class tells what to show when the navbar is collapsed. The data-toggle is picked up by bootstrap.js to give the button interactivity. The data-target specifies what actually collapses (it’s the main navbar). Finally, aria-expanded implies the button will not initially be seen.

Take a look at your progress. The images below show how the nav bar appears, collapsed and un-collapsed, on a small screen.


Leave a Reply

Your email address will not be published. Required fields are marked *