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
| Property | Why |
|---|---|
position: relative on parent | Anchors the absolutely-positioned menu. |
top: 100% on menu | Drop the menu right below the toggle. |
:focus-within | Keeps the menu open while a child is focused — keyboard friendly. |
box-shadow | Lifts 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 »</div>
</body>
</html>
Try it Yourself »
Exercise
Pin the dropdown menu directly below the toggle.
.dropdown-menu { position: absolute;
: 100%; left: 0; }
Distance from the top of the parent.
Discussion
Loading…