How to create a Hoverable Dropdown Menu Using HTML and CSS
Step 1: HTML Code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hoverable Dropdown Menu</title> <meta name="description" content="Learn how to create a hoverable dropdown menu using only HTML and CSS. No JavaScript needed! Step-by-step guide with example code."> <meta name="keywords" content="HTML CSS dropdown, hoverable dropdown, CSS dropdown menu, navigation menu, dropdown without JavaScript"> </head> <body> <!-- Navbar --> <div class="navbar"> <a href="#">Home</a> <a href="#">About</a> <div class="dropdown"> <button class="dropdown-btn">Services â–¼</button> <div class="dropdown-content"> <a href="#">Web Development</a> <a href="#">SEO Optimization</a> <a href="#">Digital Marketing</a> </div> </div> <a href="#">Contact</a> </div> <h2>Hover over the "Services" menu to see the dropdown</h2> </body> </html>
Step 2: CSS Code
body { font-family: Arial, sans-serif; text-align: center; margin: 50px; background-color: #f4f4f4; } /* Navbar styling */ .navbar { background-color: #333; padding: 15px; } .navbar a { color: white; text-decoration: none; padding: 10px 20px; display: inline-block; } /* Dropdown container */ .dropdown { position: relative; display: inline-block; } /* Dropdown button */ .dropdown-btn { background-color: #333; color: white; padding: 10px 20px; border: none; cursor: pointer; font-size: 16px; } /* Dropdown content */ .dropdown-content { display: none; position: absolute; background-color: white; min-width: 160px; box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.2); border-radius: 5px; z-index: 1000; text-align: left; } .dropdown-content a { color: black; padding: 10px 15px; text-decoration: none; display: block; transition: background 0.3s; } .dropdown-content a:hover { background-color: #ddd; } /* Show dropdown on hover */ .dropdown:hover .dropdown-content { display: block; }
Explanation
-
Dropdown Structure
- The
.dropdown
class wraps a button (.dropdown-btn
) and a hidden.dropdown-content
. - The
.dropdown-content
contains a list of links.
- The
-
CSS Styling
- The
.navbar
is styled with a dark background and white text. .dropdown-content
isdisplay: none;
by default and appears on hover..dropdown-content a
has padding and a hover effect for a smooth transition.
- The
-
Hover Effect
- The dropdown is displayed when the user hovers over
.dropdown
. - The
display: block;
inside.dropdown:hover .dropdown-content
makes it appear.
- The dropdown is displayed when the user hovers over