Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to show and hide dropdown menu on mouse hover using CSS?

The dropdown menu generally opens with a click. But we can change it using the CSS properties. In this tutorial, we will be learning about the CSS property to hide and show dropdown.

Using display and hover CSS property

The display property is used to hide and show elements in HTML. Further adding hover class to the elements adds the hover effect to the element.

Example: Hide and show dropdown menu on mouse hover

In this example, we have hidden the dropdown menu by default using display: none to the dropdown menu. further, add display: block on dropdown menu hover. Other properties are used for styling dropdown.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
	  /* Dropdown Button */
	.btn {
	  background-color: green;
	  color: white;
	  padding: 16px;
	  font-size: 20px;
	  border: 2px solid blue;
	}
	/* The dropdown class should be positioned relative */
	.dropdown {
	  position: relative;
	  display: inline-block;
	}
	/* Dropdown menu should be hidden by default */
	.dropdown-menu {
	  display: none;    /* hide the dropdown by default */
	  position: absolute;
	  background-color: #cccccc;
	  min-width: 150px;	  
	}
	/* Links inside the dropdown */
	.dropdown-menu a {
	  color: blue;
	  padding: 12px 16px;
	  text-decoration: none;
	  display: block;
	}
	/* Show the dropdown menu on hover */
	.dropdown:hover .dropdown-menu {display: block;}
	
	/* Change color of dropdown links on hover */
	.dropdown-menu a:hover {background-color: cyan;}
</style>
</head>
<body>
    <h2> Hide and show dropdown on hover </h2>
    <div class="dropdown">
	  <button class="btn">Dropdown</button>
	  <div class="dropdown-menu">
		<a href="#">courses</a>
		<a href="#">Menu</a>
		<a href="#">Link </a>
	  </div>
	</div>
</body>
</html>

Output

Here is the output of the above program.

hide and show dropdown

Example: Hide and show dropdown menu in the navbar

Conclusion

We can easily hide and show the dropdown menu using CSS. The display property along with the hover class can be used to do so.



About the author: