How to show and hide dropdown menu on mouse hover using CSS
Topic: HTML / CSSPrev|Next
Answer: Use the CSS :hover
pseudo-class
If you simply want to show and hide dropdown menu on mouse hover you don't need any JavaScript. You can do this simply using the CSS display
property and :hover
pseudo-class.
The following example will show you how to implement a simple dropdown using the CSS.
Example
Try this code »<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Show Hide Dropdown Using CSS</title>
<style>
ul {
padding: 0;
list-style: none;
background: #f2f2f2;
}
ul li {
display: inline-block;
position: relative;
line-height: 21px;
text-align: left;
}
ul li a {
display: block;
padding: 8px 25px;
color: #333;
text-decoration: none;
}
ul li a:hover {
color: #fff;
background: #939393;
}
ul li ul.dropdown {
min-width: 100%; /* Set width of the dropdown */
background: #f2f2f2;
display: none;
position: absolute;
z-index: 999;
left: 0;
}
ul li:hover ul.dropdown {
display: block; /* Display the dropdown */
}
ul li ul.dropdown li {
display: block;
}
</style>
</head>
<body>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li>
<a href="#">Products ▾</a>
<ul class="dropdown">
<li><a href="#">Laptops</a></li>
<li><a href="#">Monitors</a></li>
<li><a href="#">Printers</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
</ul>
</body>
</html>
Related FAQ
Here are some more FAQ related to this topic: