Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to create hoverable dropdown in CSS?

The dropdown menu has a list of items that can be chosen with a click. We can create a hoverable dropdown using CSS. The hover will add effects on the element when the user moves the cursor on the elements.

To add a hover effect to the elements use CSS :hover pseudo-class and add it to <a> element.

Example: Create a hoverable dropdown in CSS

In the following program, we have initially hidden the dropdown by default using display: none the property then added :hover property to dropdown-menu .

There are other properties added along with it to style the dropdown. Position: relative is added to dropdown and position:absolute to dropdown-content so that the menu opens just below the button.

<!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;
   }
	 .dropdown:hover .dropbtn {
        background-color: #4dcf45;
   }
</style>
</head>
<body>
   <h2> Create hoverable 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.

hoverable dropdown

Example: Adding dropdown in navbar

In this example, we have added the dropdown within the navbar. To do so simply add the block of dropdown within the navbar container along with other <a> elements. We have also added a caret symbol to visually represent that it has a dropdown. For that, we have added the link to the Font Awesome library.

Conclusion

In this tutorial, we have learned to create a hoverable dropdown with CSS. It can be created using :hover pseudo class. The items of the dropdown will be shown when you place the cursor over the dropdown button.



About the author: