responsive mobile friendly navigation bar

This tutorial will help you code a responsive, mobile friendly navigation bar. The format of the navigation bar is different than introduced in Coding Horizontal Navigation (.pdf). As with many things in web design, there is more than one way to do things. During the tutorial, you will:

  • create CSS to create the navigation bar
  • make the navigation bar appear differently in the 320px media query
  • add a snippet of Javascript to all HTML pages to make the menu bar work

The HTML

Unlike the navigation bars we created before, this one will not be based on lists. Here is what your HTML should look like:

<nav id="myTopnav">
  <a href="index.html" title="home">Home</a>
  <a href="about.html" title="About">About</a>
  <a href="portfolio.html" title="portfolio">Portfolio</a>
  <a href="contact.html" title="contact">Contact</a>
  <a href="javascript:void(0);" class="icon" onclick="myFunction()">&#9776;</a>
</nav>

Note that the last <a href link is required and must appear exactly as written.

The CSS

To complete this, you will be creating a new media query for a max-width of 767px. That means all screens less than 767px wide will show the modified menu. Note that this will position links to the left when on a larger screen, so in the other media queries you will need to adjust the code.

Add this code to the general area before the media queries start:

nav {
    background-color: #333;
    overflow: hidden;
}

/* Style the links inside the navigation bar */
nav a {
    float: left;
    display: block;
    color: #fff;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
}

/* Change the color of links on hover */
 nav a:hover {
    background-color: #ddd;
    color: black;
}

/* Hide the link that should open and close the topnav on small screens */
 nav .icon {
    display: none;
}

Now, add this between the min-width 320 and min-width 768 media queries:

@media screen and (max-width: 767px) {
/* When the screen is at least 320 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */
nav a:not(:first-child) {display: none;}
nav a.icon {
    float: right;
    display: block;
  }

nav.responsive {position: relative;}
nav.responsive a.icon {
    position: absolute;
    right: 0;
    top: 0;
  }
nav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
}

The Javascript

Add this code just below the navigation bar code on all HTML pages:

/* Toggle between adding and removing the "responsive" class to topnav when the user clicks on the icon */
<script>
function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}
</script>

Comments are closed.