CSS dropdown menus display hidden sub-menu lists or action panels when a user hovers over or clicks a trigger parent button.
Dropdowns rely on absolute positioning relative to a parent container:
/* Relative Parent Container */
.dropdown {
position: relative;
display: inline-block;
}
/* Hidden Absolute Sub-Menu */
.dropdown-content {
display: none;
position: absolute;
top: 100%;
left: 0;
background-color: #1e293b;
min-width: 180px;
border-radius: 6px;
box-shadow: 0 10px 15px -3px rgba(0,0,0,0.5);
z-index: 10;
}
/* Reveal Menu on Hover */
.dropdown:hover .dropdown-content {
display: block;
}
Key steps for CSS dropdowns:
position: relative on .dropdown to bind the sub-menu.position: absolute; display: none; on .dropdown-content..dropdown:hover .dropdown-content { display: block; }.flowchart TD
A["Hover over .dropdown Trigger Button"] --> B["CSS Rule: .dropdown:hover .dropdown-content"]
B --> C["Toggles display: none -> display: block"]
C --> D["Reveals Absolute Sub-Menu Overlay"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Dropdown Demonstration</title>
<style>
.dropdown {
position: relative;
display: inline-block;
}
.btn-dropdown {
background-color: #2563eb;
color: #ffffff;
padding: 10px 18px;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: bold;
}
.dropdown-menu {
display: none;
position: absolute;
top: 100%;
left: 0;
margin-top: 6px;
background-color: #1e293b;
min-width: 180px;
border-radius: 6px;
border: 1px solid #334155;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
z-index: 100;
}
.dropdown-menu a {
color: #f8fafc;
padding: 10px 16px;
text-decoration: none;
display: block;
}
.dropdown-menu a:hover {
background-color: #334155;
}
.dropdown:hover .dropdown-menu {
display: block;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<h2>Interactive Dropdown Menu</h2>
<div class="dropdown">
<button class="btn-dropdown">Account Options ▼</button>
<div class="dropdown-menu">
<a href="#">User Profile</a>
<a href="#">Settings</a>
<a href="#">Logout</a>
</div>
</div>
</body>
</html>
z-index on dropdown content: Ensures sub-menus float on top of surrounding page elements.top: 100% to align sub-menus right below buttons: Aligns dropdown menus cleanly against trigger button bottom edges.:focus-within or JavaScript click handlers for mobile users.Write a CSS rule .dropdown:hover .menu that sets display: block; to reveal a hidden sub-menu!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.