BOOTSTRAP MOBILE NAVIGATION

The navbar is designed to list links horizontally on your page. The challenge is on mobile devices you have limited horizontal space. To get around this, Bootstrap uses a dropdown menu for smaller devices, with the toggle button typically being represented as three lines, or “hamburger”.

Configuring the hamburger

To add support for the hamburger, you need to add the components that will make it up. Inside of the navbar-header, add a button configured as below.

  1. <buttontype=”button” class=”navbar-toggle collapsed” data-toggle=”collapse”>
  2. <!– placeholder –>
  3. </button>

The two classes configure the button as the toggle for the dropdown list, and collapsed by default, respectively. The data-toggle attribute targets the collapse state, meaning when you click, or tap, on it the first time it will open, and close on the second click.

Inside the button you will add the display. The first part of the display is designed for accessibility. By using the sr-only attribute, you are adding text that will not be displayed, but only read to screen readers. Then you will add in the lines that will make up the hamburger, with each line being identified with the icon-bar class.

  1. <buttontype=”button” class=”navbar-toggle collapsed” data-toggle=”collapse” data-target=”#hamburger-navigation”>
  2. <span class=”sr-only”>Navigation toggle</span>
  3. <span class=”icon-bar”></span>
  4. <span class=”icon-bar”></span>
  5. <span class=”icon-bar”></span>
  6. </button>

Adding links to the mobile dropdown

To add your existing navbar links into the dropdown list shown on mobile devices, they need to be surrounded by a container, typically div, with the collapse and navbar-collapse classes. These enable the collapsibility of the content. In addition, an id needs to be added to the div. This id will then be used by the button to toggle the display of the menu.

Adding toggle functionality to the button

The last step is to update the button to point to the div container you created above. Add the data-targetattribute, set to the value of the id you used on the div container. Remember, whenever you use a data-target, you must use the CSS selector syntax, meaning you will need to preface the id with a #.

  1. <buttontype=”button” class=”navbar-toggle collapsed” data-toggle=”collapse” data-target=”#hamburger-navigation”>
  2. <!– existing content –>
  3. </button>

 

 

FULL HTML SAMPLE

  1. <!DOCTYPE html>
  2. <htmlxmlns=”http://www.w3.org/1999/xhtml”&gt;
  3. <head>
  4. <link href=”Content/bootstrap.min.css” rel=”stylesheet” />
  5. <style>
  6. body {
  7. padding-top: 70px;
  8. }
  9. </style>
  10. <title>Navbar Sample</title>
  11. </head>
  12. <body>
  13. <nav class=”navbar navbar-default navbar-fixed-top”>
  14. Navbar Example
  15. Navigation toggle