How to Create a Dropdown Navigation Bar

As a website owner or developer, you know the importance of having a clear and user-friendly navigation system.

A dropdown navigation bar is a great way to provide users with quick access to different sections of your site.

In this tutorial, we’ll go through the steps to create a dropdown navigation bar, starting with HTML and CSS, and then we’ll add some JavaScript to make it dynamic.


HTML Structure

The first step in creating a dropdown navigation bar is to create the HTML structure.

To do this, we’ll use an unordered list (ul) with list items (li) for each menu item.

Within each list item, we’ll create another unordered list for the dropdown menu items.

Here is the HTML code for a simple dropdown navigation bar:

<ul class="navbar">
  <li><a href="#">Home</a></li>
  <li><a href="#">About</a></li>
  <li class="dropdown">
    <a href="#">Services</a>
    <ul class="dropdown-content">
      <li><a href="#">Web Design</a></li>
      <li><a href="#">Web Development</a></li>
      <li><a href="#">SEO</a></li>
    </ul>
  </li>
  <li><a href="#">Contact</a></li>
</ul>

CSS Styles

Next, we’ll add some CSS styles to make our navigation bar look good.

To make the dropdown menu appear when the user hovers over the “Services” menu item, we’ll use the :hover pseudo-class.

Here is the CSS code for the styles:

.navbar {
  list-style: none;
  display: flex;
  justify-content: space-between;
}

.navbar a {
  text-decoration: none;
  color: black;
  padding: 10px 20px;
}

.dropdown {
  position: relative;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: white;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}

JavaScript Functionality

Finally, to make our dropdown navigation bar more dynamic and accessible, we’ll add some JavaScript.

This will allow users to access the dropdown menu using the keyboard, instead of just the mouse. Here is the JavaScript code for the dropdown functionality:

const dropdown = document.querySelector('.dropdown');
const dropdownContent = document.querySelector('.dropdown-content');

dropdown.addEventListener('click', function() {
dropdownContent.classList.toggle('show');
});

window.addEventListener('click', function(event) {
if (!event.target.matches('.dropdown')) {
dropdownContent.classList.remove('show');
}
});