Signup/Sign In

How to create dropdown navigation bar with CSS?

The dropdown menu has a list of items that can be chosen with a click. We can create a dropdown by using HTML elements and CSS. So, let's learn to create a dropdown.

Creating a dropdown

The dropdown can be created using <div> container and the <button> tag to toggle the dropdown. The <a> tag is used to create the list of links inside a <div>.

  • Use position:absolute to the dropdown menu and position:relative to the dropdown content so that dropdown is placed below the button.
  • Use box-shadow property to customize dropdown like a card.
  • Use :hover class to open show the menu when the user places the mouse over it.
  • The dropdown menu is hidden by default using display:none.

Example: Creating a dropdown using CSS

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
  .dropdown-btn {
      background-color: #df4356;
	  color: black;
	  padding: 16px;
	  font-size: 20px;
	  border: none;
  }
  .dropdown {
    position: relative;
    display: inline-block;
  }
  .dropdown-menu {
    display: none;
	position: absolute;
	background-color: white;
	min-width: 150px;
	box-shadow: 5px 16px 16px 8px rgba(0,0,0,0.4);
	z-index: 1;
  }
  .dropdown-menu a {
      color: black;
	  padding: 12px 16px;
	  text-decoration: none;
	  display: block;
  } 
	 .dropdown-menu a:hover {
        background-color: #cccccc;
   }
	 .dropdown:hover .dropdown-menu {
        display: block;
   }
</style>
</head>
<body>
   <h2> Dropdown</h2>
   <div class="dropdown">
	  <button class="dropdown-btn">Dropdown</button>
	  <div class="dropdown-menu">
		<a href="#">Link 1</a>
		<a href="#">Link 2</a>
		<a href="#">Link 3</a>
	  </div>
	</div>
</body>
</html>

Output

Here is the output of the above program.

Dropdown using CSS

Example: Adding dropdown in the navigation bar

We can also create a dropdown within the navbar.

Conclusion

We can create a dropdown using CSS. We added CSS :hover class to show the dropdown contents. We can create a dropdown within the navbar using CSS properties.



About the author: