Sub topic 10
Add a dropdown submenu
This chapter adds a dropdown submenu to the navigation bar from the earlier chapters. It assumes you know these things:
- Basic HTML and CSS selectors.
- The box model.
- Flexbox, as used for the bar.
- The
:hoverand:focus-visiblestates. - The
aria-currentstyling from the previous chapters.
A dropdown looks like a small feature, but it combines positioning, state handling and accessibility. This chapter builds a CSS-only version first, then covers where it breaks and how to fix it.
How a dropdown is structured
A submenu is a list inside a list item. The parent link and its child list live in the same <li>, so they form one unit in the document. Screen readers can announce the nesting, and the browser treats pointer movement between the parent and the child list as movement inside one element.
<ul class="nav-list">
<li><a href="/">Home</a></li>
<li class="has-submenu">
<a href="/products">Products</a>
<ul class="submenu">
<li><a href="/products/software">Software</a></li>
<li><a href="/products/hardware">Hardware</a></li>
</ul>
</li>
<li><a href="/contact">Contact</a></li>
</ul>The has-submenu class is a hook for styling. The child <ul> must be a direct child of the <li> that holds the parent link, not a sibling of it. Later selectors depend on that shape.
Position the submenu
The submenu must not push the other top-level items around when it appears. It has to float over the page below the bar. Two positioning properties do this:
position: relativeon the parent item makes it the reference box for its descendants.position: absoluteon the submenu removes it from normal flow and places it relative to that reference box.
.has-submenu {
position: relative;
}
.submenu {
display: none;
position: absolute;
top: 100%;
left: 0;
min-width: 12rem;
margin: 0;
padding: 0;
list-style: none;
background: #1f2937;
}
.has-submenu:hover > .submenu,
.has-submenu:focus-within > .submenu {
display: block;
}Here is what each part does:
top: 100%places the top edge of the submenu at the bottom edge of the parent item. The percentage refers to the height of the positioned parent, so it works however tall the bar is.left: 0aligns the left edges of the parent and the submenu.min-width: 12remkeeps short labels from producing a narrow, cramped menu. Longer labels still make the menu wider.- The
margin,paddingandlist-stylelines repeat the list reset from earlier. A nested<ul>gets the browser's default bullets and indentation again unless you reset it. display: nonehides the submenu by default.
The submenu links need no new styling. The rule .nav-list a from the earlier chapters is a descendant selector, so it already matches links in the submenu. They get display: block, the padding, the white text, and the hover and focus rules.
If you want the submenu items to stay on one line each, add white-space: nowrap to .submenu a. Without it, a long label wraps inside the min-width box.
Why two selectors open the menu
The last rule has two selectors, and each one covers a different kind of user.
:hoveropens the menu when a pointer is over the parent item. Because the submenu is a descendant of.has-submenu, the pointer is still "hovering" the parent while it moves over the submenu. The menu does not close when you move down to a child link.:focus-withinmatches an element when it, or any element inside it, has focus. When a keyboard user tabs to the Products link, the item matches, and the submenu opens. Pressing Tab again moves focus into the first submenu link. The item still contains the focused element, so the menu stays open.
The child combinator > limits the rule to the submenu directly under the hovered item. This matters once you nest a third level, because without > hovering a top-level item would open every list below it.
The hover gap problem
A common bug makes the menu disappear when the user tries to reach it. It happens when there is empty space between the parent and the submenu. For example, you add margin-top: 0.5rem to .submenu for visual separation. While the pointer crosses that gap, it is over neither the parent nor the submenu, so :hover stops matching and display goes back to none.
The same applies to top. Keep it at 100%, with no extra offset.
Clipping and stacking
Two other things can hide a submenu that is otherwise correct.
- Clipping. If the
<nav>or any ancestor hasoverflow: hidden,overflow: autooroverflow: scroll, the submenu is cut off at that ancestor's edge, because the absolutely positioned child still lives inside it. Remove the overflow rule, or move the overflow handling to a different element. - Stacking. The submenu must draw above the page content. The sticky bar from a later chapter sets
z-index: 10onnav. That creates a stacking context for everything inside it, so the submenu rises with the bar and appears over the content without needing its ownz-index. If you build a bar without az-indexon thenav, positioned content later in the page can paint over the submenu. Give thenavapositionand az-indexin that case.
What the CSS-only version gets wrong
The version above works for a mouse and for a keyboard, but it has limits you should know about before shipping it.
| Issue | Effect | Fix |
|---|---|---|
| No Escape key | A keyboard user cannot close the menu without moving focus away | Add JavaScript for Escape |
| `display: none` on the submenu | Hidden links are removed from the tab order and from the accessibility tree, which is correct, but nothing tells assistive technology that the parent has a submenu | Use a button with `aria-expanded` |
| Touch screens | There is no hover. A tap on the parent link may follow its URL instead of opening the menu, or may open the menu only after an inconsistent double tap | Use a button that toggles the menu |
| Opens on focus | A user tabbing through the bar has to tab through every submenu link before reaching the next top-level item | Open only on an explicit action |
The Web Content Accessibility Guidelines (WCAG) 1.4.13 sets rules for content that appears on hover or focus. It must be dismissible without moving the pointer or focus, hoverable (the pointer can move onto it without it vanishing), and persistent until the user dismisses it. The CSS-only version satisfies "hoverable" and "persistent", but not "dismissible".
A more robust version with a toggle button
The usual fix is to separate the two jobs. The link navigates to the Products page, and a separate button opens and closes the submenu. This is the same pattern as the mobile menu toggle in a later chapter, applied to a single item.
<li class="has-submenu">
<a href="/products">Products</a>
<button class="submenu-toggle" aria-expanded="false" aria-controls="products-menu" aria-label="Products submenu">▾</button>
<ul class="submenu" id="products-menu">
<li><a href="/products/software">Software</a></li>
<li><a href="/products/hardware">Hardware</a></li>
</ul>
</li>The button is a real <button>, so it is focusable and responds to Enter and Space without extra work. The aria-label gives it a name, because the visible ▾ character is not a useful label for a screen reader. aria-controls points to the submenu's id, and aria-expanded reports the current state.
The CSS changes in three ways. The parent item becomes a flex container so the link and button sit side by side, the button gets the same look as the links, and the submenu opens on a class instead of on :focus-within.
.has-submenu {
position: relative;
display: flex;
}
.submenu-toggle {
padding: 0 0.75rem;
border: 0;
background: transparent;
color: #ffffff;
font: inherit;
cursor: pointer;
}
.submenu-toggle:hover,
.submenu-toggle:focus-visible {
background: #374151;
}
.submenu-toggle:focus-visible {
outline: 2px solid #38bdf8;
outline-offset: -2px;
}
.has-submenu.is-open > .submenu {
display: block;
}Remove the :focus-within selector from the earlier rule. If you keep it, focusing the button opens the menu, and the aria-expanded value no longer matches what is on screen. You can keep :hover for pointer users if you like, but then a mouse user can see the menu open while aria-expanded still says false. The simplest consistent choice is to drop both selectors and let the class control everything.
The script keeps the class and the attribute in step, closes the menu on Escape, and closes it when focus leaves the item.
document.querySelectorAll('.has-submenu').forEach((item) => {
const button = item.querySelector('.submenu-toggle');
const setOpen = (open) => {
button.setAttribute('aria-expanded', String(open));
item.classList.toggle('is-open', open);
};
button.addEventListener('click', () => {
setOpen(button.getAttribute('aria-expanded') !== 'true');
});
item.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
setOpen(false);
button.focus();
}
});
item.addEventListener('focusout', (event) => {
if (!item.contains(event.relatedTarget)) {
setOpen(false);
}
});
});Two details in this script are easy to get wrong:
- On Escape, the script returns focus to the button. If the user was inside the submenu, that link becomes
display: noneand focus would otherwise be lost, which sends keyboard users back to the top of the page. - The
focusouthandler checksevent.relatedTarget, the element receiving focus. Moving between two links inside the item is not leaving it, so the menu stays open. Clicking outside the page (whererelatedTargetisnull) closes it.
Choosing between the two versions
Use the CSS-only version when the menu is small, the audience is mostly on desktop, and you accept the limits in the table. It has no script to maintain and works if JavaScript fails to load. Use the button version when touch users matter, when the site has to meet WCAG 2.1 AA, or when the parent link must stay a working link. Most production sites end up with the button version.
Also keep submenus shallow. One level is usually enough. A third level multiplies the hover-gap and clipping problems and is hard to use on touch screens.
Common errors
- The submenu appears in the page flow and pushes content down. The parent has no
position: relative, or the submenu has noposition: absolute. - The submenu opens at the page edge instead of under its parent. The positioning context is missing, so
top: 100%is measured from the nearest positioned ancestor, or from the page. - The menu closes while the pointer moves to it. There is a gap, as described above.
- Submenu links show bullets or indentation. The reset is missing on
.submenu. - The submenu is cut off. An ancestor has an
overflowvalue other thanvisible. - Opening a submenu opens all of them. The selector lacks the
>child combinator, or the class is applied to the wrong element.
Exercise
A submenu opens when you hover the parent item, but it closes as soon as you move the pointer down toward it. The CSS includes .submenu { top: 100%; margin-top: 0.5rem; }. Explain why it closes, and give a fix that keeps a visual separation.
Show answer
The 0.5rem margin leaves an empty strip between the parent item and the submenu. While the pointer crosses it, it is over neither element, so .has-submenu:hover no longer matches and the submenu returns to display: none. Remove the margin and keep top: 100%. For visual separation, add a border-top to the submenu (or a box-shadow), so there is no gap in the hover area.
Exercise
In the toggle-button version, why should you remove .has-submenu:focus-within > .submenu from the CSS?
Show answer
With :focus-within, focusing the button opens the menu through CSS, but the script has not run, so aria-expanded still says false. The visual state and the announced state disagree. Removing the selector makes the is-open class, set together with aria-expanded, the only thing that opens the menu.