Loading lessons...
Dropdown Menus
Dropdown Menus
A hidden panel that appears when you hover or focus a button. No JavaScript needed!
The HTML structure
<div class="dropdown">
<button class="dropbtn">Menu</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
</div>
</div>
The CSS
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
position: absolute;
display: none; /* hidden by default */
min-width: 160px;
background-color: #f9f9f9;
box-shadow: 0 8px 16px rgba(0,0,0,0.2);
}
.dropdown:hover .dropdown-content,
.dropdown:focus-within .dropdown-content {
display: block; /* appears on hover/focus */
}
Key points
- The container is
position: relative(anchor). - The panel is
position: absoluteso it floats. - Reveal with
:hoverAND:focus-within, the:focus-withinpart keeps it keyboard-accessible! - Add
z-indexso the panel sits above other content.
Effects
box-shadowlifts it visually.- Add a
transitionon opacity for smoothness.
Advanced: click with focus
.dropdown-content {
display: none;
}
.dropdown:focus-within .dropdown-content {
display: block;
}
TL;DR
- Container = relative, panel = absolute, hidden with
display: none. - Show on
:hoverAND:focus-withinfor accessibility. - Use
z-indexandbox-shadowto make it feel like a real menu. - No JS needed for basic dropdowns!