Lesson 64 +10 XP

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: absolute so it floats.
  • Reveal with :hover AND :focus-within, the :focus-within part keeps it keyboard-accessible!
  • Add z-index so the panel sits above other content.

Effects

  • box-shadow lifts it visually.
  • Add a transition on 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 :hover AND :focus-within for accessibility.
  • Use z-index and box-shadow to make it feel like a real menu.
  • No JS needed for basic dropdowns!