
In this post, we will learn about creating a dropdown menu inside a navbar.
A little bit about dropdown –
A dropdown is a togglable menu where you put a list of items. When a user clicks on the dropdown button, the menu becomes visible, then the user can choose an item from that menu. Bootstrap dropdown JavaScript plugin makes it interactive.
Now, let’s see the code.
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">
<title>Dropdown inside navbar</title>
</html>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#myNavbar" aria-controls="myNavbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link" href="#">Home</a></li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Products
</a>
<ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink">
<li><a class="dropdown-item" href="#">Shirts</a></li>
<li><a class="dropdown-item" href="#">T-shirts</a></li>
<li><a class="dropdown-item" href="#">Watches</a></li>
</ul>
</li>
<li class="nav-item"><a class="nav-link" href="#">About us</a></li>
<li class="nav-item"><a class="nav-link" href="#">Contact us</a></li>
</ul>
</div>
</div>
</nav>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous">
</script>
</body>
Output:
Before clicking on the dropdown.

After clicking on the dropdown.

Here, I have created a navbar with four menus – Home, Products, About Us, and Contact Us. The second menu, Products, is a dropdown menu. When I clicked on the Products, it shows 3 menus – Shirts, T-shirts, and Watches.
Leave a Reply