How to create: Responsive top navigation bar

Learn how to create a responsive top navigation bar using CSS and JavaScript.

Responsive top navigation menu

Adjust the browser window size to see how the responsive navigation menu works:

Try It Yourself

Create a responsive top navigation menu

Step 1 - Add HTML:

/* Load the icon library to display the hamburger menu (bar) on small screens */
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="topnav" id="myTopnav">
  <a href="#home" class="active">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
  <a href="javascript:void(0);" class="icon" onclick="myFunction()">
    <i class="fa fa-bars"></i>
  </a>
</div>

Links with class "icon" are used to open and close the top navigation on small screens.

Step 2 - Add CSS:

/* Add a black background color to the top navigation */
.topnav {
  background-color: #333;
  overflow: hidden;
}
/* Set the style of links in the navigation bar */
.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}
/* Change the color of the link when the mouse hovers over it */
.topnav a:hover {
  background-color: #ddd;
  color: black;
}
/* Add an active class to highlight the current page */
.topnav a.active {
  background-color: #04AA6D;
  color: white;
}
/* Hide the link used to open and close the top navigation on small screens */
.topnav .icon {
  display: none;
}

Add media query:

/* When the screen width is less than 600 pixels, hide all links except the first one ("Home") and display the link that opens and closes the top navigation (.icon). */
@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {display: none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
}
/* When the user clicks on the icon, JavaScript will add the "responsive" class to topnav. This class makes topnav look better on small screens (the links are displayed vertically instead of horizontally). */
@media screen and (max-width: 600px) {
  .topnav.responsive {position: relative;}
  .topnav.responsive a.icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
}

Step 3 - Add JavaScript:

/* When the user clicks on the icon, toggle the addition and removal of the "responsive" class on topnav */
function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  }
    x.className = "topnav";
  }
}

Try It Yourself

Related Pages

Tutorial:CSS Navigation Bar