Autocomplete Suggestions Anchored to an Input

Anchor an autocomplete suggestions dropdown to the input element with min-width matched to the input width.

UI Patterns

Detailed Explanation

The Pattern

An <input> is the anchor; the suggestions <ul> is the target. The list must:

  1. Sit directly below the input (no gap, like a native <select>)
  2. Match the input's width exactly
  3. Flip upward if it would overflow the viewport bottom
.search-input {
  anchor-name: --search;
}

.suggestions {
  position: absolute;
  position-anchor: --search;
  position-area: bottom-start;

  /* Width strategy: match the input exactly */
  width: anchor-size(width);

  background: var(--surface);
  border: 1px solid var(--border);
  border-top: none; /* shared edge with input */
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  max-height: 320px;
  overflow-y: auto;

  position-try-fallbacks: flip-block;
}

/* When flipped, swap the rounded corners */
.suggestions:where(@position-try) {
  border-top: 1px solid var(--border);
  border-bottom: none;
  border-radius: 4px 4px 0 0;
}

width: anchor-size(width)

This makes the suggestions list exactly as wide as the input, regardless of how the input is sized (fixed pixels, flex-grow, percentage). It's the equivalent of measuring the input width with JavaScript and applying it to the dropdown — but it's free, declarative, and updates automatically on resize.

Keyboard interaction

Anchor positioning is purely visual. You still need to:

  • Manage role="combobox" on the input and role="listbox" on the suggestions
  • Use aria-activedescendant to track the focused suggestion
  • Handle ArrowDown / ArrowUp to move the active item
  • Handle Enter to select and Escape to dismiss

The Combobox pattern from WAI-ARIA Authoring Practices is a comprehensive reference.

Performance note

Anchor positioning re-runs on layout changes. If your suggestions list re-renders 60 times a second on every keystroke (e.g. fuzzy-searching 10K items), the anchor work itself is negligible — it's the React re-render that costs. Profile in Chrome DevTools' Performance tab if you suspect anchoring is slow; in 99% of cases it isn't.

Use Case

Search bars with live suggestions, command palettes (Ctrl+K menus), tag/chip input fields, mention autocomplete in comment boxes, address autocomplete in shipping forms, GitHub-style file finder.

Try ItCSS Anchor Positioning Generator

Open full tool