How to create a multi-level dropdown menu in CSS

Arif Billah Babu

         

  CSS



Image not found!!

Creating a multi-level dropdown menu in CSS involves using nested HTML lists (<ul> and <li>) and utilizing CSS for styling and positioning. Here's a simple example:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> /* Reset some default styles */ * { margin: 0; padding: 0; box-sizing: border-box; } /* Style the navigation bar */ nav { background-color: #333; } /* Style the top-level menu items */ nav ul { list-style: none; display: flex; } nav ul li { position: relative; padding: 15px; color: white; cursor: pointer; } /* Style the dropdown menus */ nav ul ul { display: none; position: absolute; top: 100%; left: 0; background-color: #555; } nav ul ul li { width: 200px; float: none; display: list-item; position: relative; } /* Show the dropdown menus on hover */ nav ul li:hover > ul { display: inherit; } /* Style links within the dropdown menus */ nav ul ul a { color: white; padding: 10px; text-decoration: none; display: block; } nav ul ul a:hover { background-color: #777; } </style> </head> <body> <nav> <ul> <li>Home</li> <li>About <ul> <li>History</li> <li>Team</li> </ul> </li> <li>Services <ul> <li>Web Design</li> <li>Graphic Design</li> </ul> </li> <li>Contact</li> </ul> </nav> </body> </html>

In this example:

  • The top-level menu items are styled with a background color of #333.
  • The dropdown menus (nav ul ul) are initially set to display: none; to hide them.
  • When you hover over a top-level menu item (nav ul li), its nested dropdown menu (nav ul ul) becomes visible (display: inherit;).
  • Adjust the styles and colors as needed to match your design preferences.

Feel free to customize the code further based on your specific design requirements.