How to Create a Responsive Top Navigation Menu with CSS and JavaScript

A top navigation menu is a crucial component of modern websites and web applications.

The menu serves as a way for users to navigate through the website and access its different pages and sections.

A top navigation menu should be designed to be user-friendly and responsive, so that it works well on different devices and screen sizes.

In this tutorial, we will show you how to create a responsive top navigation menu using CSS and JavaScript.


HTML Markup

The first step in creating a top navigation menu is to create the HTML markup for it.

A typical top navigation menu is composed of a series of links that lead to different pages or sections of the website.

In this example, we will create a menu with four links: Home, About, Services, and Contact.

<header>
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Services</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>

Styling with CSS

Next, we will use CSS to style the top navigation menu.

We will start by giving the menu a fixed position at the top of the page and setting its width to 100% of the viewport.

We will also give the links a horizontal layout using the display: inline-block property and style them using font and color properties.

header {
position: fixed;
top: 0;
width: 100%;
background-color: #333;
}

nav ul {
margin: 0;
padding: 0;
list-style: none;
position: relative;
}

nav ul li {
display:inline-block;
background-color: #333;
width: 25%;
float: left;
}

nav a {
display: block;
padding: 0 10px;
color: #fff;
font-size: 20px;
line-height: 60px;
text-decoration: none;
}

Responsiveness with JavaScript

The final step is to make the top navigation menu responsive using JavaScript.

We will use a JavaScript function to toggle the visibility of the menu when the screen size is less than a certain width.

We will use media queries in CSS to hide the menu on small screens and show a hamburger icon that will trigger the JavaScript function.

// JavaScript function to toggle menu visibility
function toggleMenu() {
var menu = document.querySelector("nav ul");
menu.classList.toggle("show");
}
// Media query to hide menu on small screens
@media (max-width: 600px) {
header nav ul {
display: none;
}

header nav button {
display: block;
}

// Show menu on click of hamburger icon
header nav button:hover {
cursor: pointer;
}
}

// CSS class to show menu
.show {
display: block;
}

Conclusion

In this tutorial, we have shown you how to create a responsive top navigation menu using HTML, CSS, and JavaScript.