iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Dropdowns

A pure-CSS dropdown reveals a menu when the parent is hovered or focused. No JavaScript required for the basic version.

HTML

HTML
<div class="dropdown">
  <button class="dropdown-toggle">Account ▾</button>
  <ul class="dropdown-menu">
    <li><a href="/profile">Profile</a></li>
    <li><a href="/settings">Settings</a></li>
    <li><a href="/logout">Sign out</a></li>
  </ul>
</div>

CSS

CSS
.dropdown { position: relative; display: inline-block; }
.dropdown-menu {
  position: absolute; top: 100%; left: 0;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 6px 16px rgba(0,0,0,0.1);
  list-style: none;
  margin: 4px 0 0; padding: 4px 0;
  min-width: 180px;
  display: none;
}
.dropdown:hover    .dropdown-menu,
.dropdown:focus-within .dropdown-menu { display: block; }
.dropdown-menu li a { display: block; padding: 8px 14px; color: #000; text-decoration: none; }
.dropdown-menu li a:hover { background: #f1f1f1; }

Why these properties

PropertyWhy
position: relative on parentAnchors the absolutely-positioned menu.
top: 100% on menuDrop the menu right below the toggle.
:focus-withinKeeps the menu open while a child is focused — keyboard friendly.
box-shadowLifts the menu visually so it reads as a layer.
Accessibility: Production dropdowns add JavaScript for keyboard support (arrow keys, Escape) and ARIA attributes. The CSS above gets you 80% there.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Dropdowns</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Pin the dropdown menu directly below the toggle.

.dropdown-menu { position: absolute; : 100%; left: 0; }

Test yourself

Q1. Which combination opens the dropdown on hover with pure CSS?
Q2. Why use `:focus-within` on the parent as well as `:hover`?
Q3. The dropdown menu is positioned `absolute` — what makes it anchor to the toggle?

Discussion

Loading…