Create a Responsive & Cross-Browser Dropdown Nav Menu
by jay prakash
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Dropdown Navigation</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js" defer></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
</head>
<body>
<header>
<nav class="nav-container">
<div class="logo">
<img src="assets/logo.png" alt="Logo">
</div>
<button class="menu-toggle">
<i class="fas fa-bars"></i>
</button>
<ul class="nav-menu">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li class="dropdown">
<a href="#">Services <i class="fas fa-chevron-down"></i></a>
<ul class="dropdown-menu">
<li><a href="#">Web Design</a></li>
<li><a href="#">SEO</a></li>
<li><a href="#">Marketing</a></li>
</ul>
</li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
</body>
</html>
CSS
/* Default */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}
/* Navigation */
.nav-container {
display: flex;
justify-content: space-between;
align-items: center;
background: #012b3b;
padding: 15px 20px;
position: relative;
}
.logo img {
height: 50px;
}
/* Menu Items */
.nav-menu {
display: flex;
list-style: none;
}
.nav-menu li {
position: relative;
}
.nav-menu a {
text-decoration: none;
color: white;
padding: 12px 18px;
display: block;
transition: background 0.3s;
}
.nav-menu a:hover {
background: #ec7f03;
}
/* Dropdown Menu */
.dropdown-menu {
position: absolute;
left: 0;
top: 100%;
background: #034a69;
min-width: 200px;
list-style: none;
display: none;
}
.dropdown-menu li {
border-bottom: 1px solid #0b6688;
}
.dropdown-menu a {
padding: 10px;
color: white;
}
.dropdown:hover .dropdown-menu {
display: block;
}
.menu-toggle {
display: none;
font-size: 24px;
background: none;
border: none;
color: white;
cursor: pointer;
}
/* Responsive Menu */
@media screen and (max-width: 767px) {
.nav-menu {
display: none;
flex-direction: column;
width: 100%;
background: #012b3b;
position: absolute;
top: 60px;
left: 0;
z-index: 100;
}
.nav-menu.show {
display: flex;
}
.dropdown-menu {
position: relative;
display: block !important;
background: none;
padding-left: 20px;
}
.dropdown-menu li {
border: none;
}
.dropdown-menu a {
padding-left: 25px;
}
.menu-toggle {
display: block;
}
}
JavaScript
$(document).ready(function () {
// Toggle mobile menu
$(".menu-toggle").click(function () {
$(".nav-menu").toggleClass("show");
});
// Hide menu when clicking outside
$(document).click(function (event) {
if (!$(event.target).closest("nav").length) {
$(".nav-menu").removeClass("show");
}
});
});