CSS anchor-size(): Match a Dropdown's Width to Its Button
Dropdown width that matches its button
Matching a menu to its button used to mean measuring the button in JavaScript, writing an inline width, and doing it again whenever the label changed. anchor-size() reads the width straight off the button, so the menu always lines up.
The old hack vs the modern fix
View demo.select-menu {
position: absolute;
min-width: var(--button-width);
}
/* JS: measure the button and write its width */
const w = button.getBoundingClientRect().width;
menu.style.setProperty('--button-width', w + 'px');
/* then a ResizeObserver to redo it when the label or font changes */.select-button {
anchor-name: --select;
}
.select-menu {
position: absolute;
position-anchor: --select;
position-area: bottom span-right;
min-width: anchor-size(width);
}
/* as wide as the button, no measuring */Anchor positioning browser support
Everything on this page works in Chrome and Edge 129, Firefox 147 and Safari 26. Baseline lists anchor positioning as a whole as limited because only Safari supports every position-visibility value, which this snippet doesn't use.
Live demo
Why the modern way wins
Stays in sync
If the button's label gets longer or a web font loads late, the menu width follows. Nothing has to watch the button for changes.
Any dimension
anchor-size() takes width, height, block or inline, so it handles tall anchors and vertical writing modes too.
Works in calc()
It's a plain length, so calc(anchor-size(width) + 2rem) works when you want the menu a little wider than its button.
- Old Approach
- Measure in JS
- getBoundingClientRect + ResizeObserver
- Modern Approach
- anchor-size()
- Reads the anchor's size
How it works
anchor-size() returns a length taken from an element's anchor. You can use it in sizing, inset and margin properties on an absolutely or fixed positioned element that's tied to an anchor with position-anchor. anchor-size(width) gives you the anchor's width, and anchor-size(height) gives you its height.
Using min-width instead of width lets the menu grow when one option is longer than the button, while never getting narrower than it. position-area: bottom span-right puts the menu below the button with its left edge lined up with the button's left edge.
If the menu opens with the popover attribute, reset inset to auto and set your own margin. The browser's default popover styles center it in the viewport with inset: 0 and margin: auto, and those fight the anchored position. See the anchor-size() reference for every argument.
Older browsers ignore anchor-size(), so the whole declaration is dropped. A fixed fallback like min-width: 12rem written before it keeps the menu usable there.