跪拜 Guibai
← Back to the summary

CSS Anchor Positioning Reaches Production: No More Manual Coordinate Math for Popups

No More Manual Coordinate Math for Popups: CSS Anchor Positioning from Principle to Production

Author: 牧艺 Tags: CSS, Frontend, JavaScript

Release date: 2026-11-12
Tags: Frontend / CSS / Anchor Positioning / Popover / Engineering Practice

1. Opening: Coordinate Calculation Still Runs on the Main Thread

You click the "More" button in the last row of a table, and a menu pops up below the button, only to get cut in half by the viewport's bottom edge. So you write a piece of getBoundingClientRect, subtract the scroll offset, and decide to flip the menu above the button. As soon as there are multiple scroll containers, this code starts to grow hair: you have to listen for resize, scroll, a parent transform turns fixed into a local coordinate system, and when a virtual list recycles a node, the button element is replaced while your listeners are still attached to the old one.

This isn't because some library was poorly written. As long as the popup and the anchor are in two different subtrees, "where is the anchor, where should the popup go, and how do we flip when it hits the edge" is a layout problem. For the last ten years, front-end developers have patched this layout problem with JavaScript: Popper, Floating UI, and various internal usePopper hooks. They are reliable, but expensive — every scroll recalculates on the main thread, every design system wraps another layer, and arrow, flip, collision, and hide conditions all become middleware.

On January 13, 2026, CSS Anchor Positioning became Baseline Newly Available: Chrome/Edge 125+, Safari 26+, Firefox 147+ — all three engines now share the same capability. position-area and position-try-fallbacks were also aligned on that day. For the first time, popup positioning can be written as styles, not as frame-by-frame measurement.

This article doesn't paraphrase the spec. It only answers four questions: what exactly is the browser calculating for you, how does it integrate with the Popover API, what pitfalls exist in lists and scrolling, and when should you still keep Floating UI in your dependencies.

Here's a comparison table first. Today is November 2026; Baseline has been live for ten months, but your internal browser baseline may not have caught up.

Approach Who calculates position Cost while scrolling Flip / overflow prevention Suitable for
Hand-written getBoundingClientRect Main thread Listen on every scroll container Write it yourself One-off scripts
Floating UI / Popper Main thread autoUpdate continuously measures Middleware is comprehensive Virtual references, complex arrows, older browsers
CSS Anchor Positioning Browser layout Rebuilds along with the anchor position-try-fallbacks Buttons, menus, tooltips, labels that follow DOM

The conclusion is direct: if the anchor is a real DOM box and your browser is within Baseline, let CSS do the positioning. If the anchor is a cursor, a text selection, a projected point in a Canvas, or you must support pre-2025 Chrome, hand the measurement back to JavaScript.


2. How It Works: The Browser Only Needs "Anchor" and "The Anchored"

2.1 Two Names, One Layout Pass

Anchor Positioning splits the participants into two roles.

The anchor gives itself a dashed identifier via anchor-name. The positioned element uses position-anchor to point to that name, and must itself be absolutely or fixed positioned. Then you stop writing magic top / left numbers and instead tell the browser: I want to stick to which edge of the anchor.

.more-btn {
  anchor-name: --more;
}

.menu {
  position: absolute;
  position-anchor: --more;
  position-area: block-end center;
  margin: 8px 0 0 0;
}

position-area treats the anchor as the center cell of a nine-grid. block-end center means "aligned to the end of the anchor's block axis, centered on the inline axis" — in a horizontal document, that's directly below the button, horizontally centered. It used to be called inset-area; during the Chromium transition both names are recognized, but new code should use position-area.

You can also skip the grid and use the anchor() function to tie a specific edge:

.menu {
  position: absolute;
  position-anchor: --more;
  top: anchor(bottom);
  left: anchor(left);
  margin-top: 8px;
}

anchor(bottom) means: my top aligns with the anchor's bottom edge. If the grid is enough, use position-area; it's short and shares the same language as flip keywords. Only when you need fine control like "align to the left and follow the anchor's width" would you fall back to anchor() and anchor-size().

Here's a fact that must be written into team guidelines: always explicitly set position-anchor. All three engines once gave this property different initial values — implicit, auto, none — and Chrome only aligned to the spec's normal in version 151. If the name is written in the declaration, that history doesn't matter to you.

2.2 When It Doesn't Fit, the Browser Tries the Next Cell

When a button is flush against the viewport bottom, the menu shouldn't be clipped. position-try-fallbacks gives a set of fallback positions. If the default position doesn't fit, the browser goes through them in order and picks the first one that no longer overflows the "inset-modified containing block." If none fit, it reverts to your written default position.

.menu {
  position-area: block-end center;
  margin: 8px 0 0 0;
  position-try-fallbacks: flip-block;
}

flip-block mirrors along the block axis: if it doesn't fit below, flip above, and the margin mirrors too, so margin-top: 8px becomes the 8-pixel gap at the bottom after flipping. You don't need a separate "above-specific margin." flip-inline mirrors along the inline axis. Separate the two keywords with a space to flip both axes in the same attempt; separate them with a comma to make two distinct attempts.

Fallback positions can also be written as nine-grid cells, or as named @position-try blocks:

@position-try --above {
  position-area: block-start center;
  margin: 0 0 8px 0;
}

.menu {
  position-area: block-end center;
  margin: 8px 0 0 0;
  position-try-fallbacks: --above;
}

@position-try is not a full stylesheet. The spec only lets it change six categories of declarations: inset, margin, size, self-alignment, position-anchor, and position-area. It can move and shrink the box, but it cannot change colors, swap text, or alter content when flipping. If your tooltip arrow needs to "point up when below, point down when above," you can't rely on this rule to also flip the pseudo-element. Either accept the arrow always pointing toward the anchor's center (align with anchor-center), or modify size and inset in fallback positions and simulate with two pseudo-element clippings. That's already the decoration layer, not something to stuff into the positioning layer.

2.3 Why It's Cheaper Than Measurement

The JavaScript cycle is: layout completes → read geometry → write top/left → possibly trigger layout again. Scrolling and zooming both rerun this cycle, which is why Floating UI needs autoUpdate.

Anchor Positioning happens inside the layout phase. When the anchor's box changes, positioned elements that depend on it update in the same layout pass. You never read geometry, so there's no opportunity for forced synchronous layout. When a button moves inside a scroll container, the menu follows without you attaching a scroll listener.

The trade-off is also clear: the browser will only flip when it doesn't fit; it won't do Floating UI's business policies like "stay in the viewport as much as possible, don't cover a selection, and have the arrow point at the third character." If your strategy is complex, keep using middleware.


3. A Tooltip That Can Ship

Below is a hint that works on hover and keyboard focus, and doesn't rely on popover attributes. The anchor is a button, and the hint is a sibling that follows it.

<span class="tip-host">
  <button type="button" class="tip-anchor">保存草稿</button>
  <span class="tip" role="tooltip">已写入本地,可稍后发布</span>
</span>
.tip-anchor {
  anchor-name: --tip;
}

.tip {
  position: absolute;
  inset: auto;
  margin: 0 0 8px 0;
  width: max-content;
  max-width: 240px;
  padding: 6px 8px;
  border-radius: 6px;
  background: #1f2329;
  color: #fff;
  font-size: 12px;
  line-height: 1.5;

  opacity: 0;
  pointer-events: none;
  transition: opacity 120ms linear;
}

.tip-host:hover .tip,
.tip-host:focus-within .tip {
  opacity: 1;
}

@supports (anchor-name: --tip) and (position-area: top) {
  .tip {
    position-anchor: --tip;
    position-area: block-start center;
    position-try-fallbacks: flip-block;
    position-visibility: anchors-visible;
  }
}

Several implementation constraints are better written into comments than into your memory:

  1. Progressive enhancement goes outside @supports. Unsupported browsers get position: absolute plus a static offset you provide separately (like bottom: calc(100% + 8px) relative to .tip-host). Supported browsers then hand inset back to position-area. Testing only anchor-name isn't enough: Chrome 125 recognizes it, but position-area only arrives in 129, and position-try-fallbacks in 128. If you use all three, put all three in the condition. In practice, testing anchor-name plus position-area already filters out the "half-supported" Chromium builds.
  2. position-visibility: anchors-visible. Once the anchor scrolls out of the visible area, the hint shouldn't float in the viewport pointing at nothing. This value is exactly for that. Safari 26.2 and Firefox 147 align with Chrome; earlier Safari 26 ignores it, and the hint just stays — not a layout break.
  3. Place the hint after the anchor. The spec requires that, in the same containing block, the anchor must complete layout before the positioned element. Writing "button first, hint second" in source order satisfies this. Portaling the hint to the end of document.body also works, as long as the anchor appears earlier in document order.
  4. Don't toggle with display: none. When either anchor or hint is removed via display: none, the anchor relationship is invalidated and positioning falls back to the nearest positioned ancestor. Use opacity, visibility, or the popover's top layer for show/hide. Don't yank the box out of the formatting structure.

4. Connecting with the Popover API: Click-Open Menus

For hover hints, a sibling node is enough. A click-open menu needs: top layer, close on outside click, and focus returning to the button. These are the Popover API's job, not Anchor Positioning's. Combining the two APIs is what forms the "More" menu in a design system.

<button
  type="button"
  class="more-btn"
  popovertarget="row-menu"
  style="anchor-name: --row-menu"
>
  更多
</button>
<div id="row-menu" popover class="menu">
  <button type="button">复制链接</button>
  <button type="button">移入回收站</button>
</div>
.menu {
  position: fixed;
  inset: unset;
  margin: 8px 0 0 0;
  width: max-content;
  min-width: 160px;
  padding: 4px;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  background: #fff;

  position-anchor: --row-menu;
  position-area: block-end span-inline-end;
  position-try-fallbacks: flip-block, flip-inline;
  position-visibility: anchors-visible;
}

Popover's UA styles default to "fill the viewport and center with margin: auto." If you don't reset inset and margin, position-area will be canceled by that centering, and the menu will sit in the middle of the screen looking like the anchor didn't work. inset: unset plus a spacing addition is the first line of code when connecting to Popover.

popovertarget also gives the popover an implicit anchor, which is that button. The implicit anchor is only used when you write position-anchor: auto. The example above deliberately avoids the implicit anchor and writes --row-menu instead. The reason is specific: if a table row has both "More" and "Share" buttons, the implicit anchor changes with whichever button was last opened, and someone reading the styles can't tell which button the current menu is attached to. When the name is written on the button, the relationship lives in the HTML, and code review can see it.

position-area: block-end span-inline-end places the menu below the button and expands along the inline-end. For right-aligned action columns, this is less likely to hit the table's right edge than horizontal centering. flip-block, flip-inline are two attempts: first try flipping vertically, then horizontally if it still overflows.


5. Duplicate Anchor Names in Lists Overwrite Each Other

Writing a component like this is natural:

.row-action { anchor-name: --row-menu; }
.row-menu { position-anchor: --row-menu; }

Once a hundred rows render, the page has a hundred --row-menu identifiers. The spec's conflict resolution: same-named anchors, the positioned element binds to the last one in tree order. So every row's menu goes looking for the last row's button. This bug doesn't show up on the first screen; you only find it after scrolling to the bottom.

The solution is anchor-scope, which scopes name visibility to a component subtree:

.row {
  anchor-scope: --row-menu;
}

.row .row-action {
  anchor-name: --row-menu;
}

.row .row-menu {
  position-anchor: --row-menu;
}

Each row becomes its own scope, and the --row-menu inside a row no longer leaks to the next. This is different from Shadow DOM encapsulation: anchor-scope limits name lookup within the same document tree. Anchor names still don't cross Shadow boundaries. If a Web Component places the button and menu in two separate shadow roots, an external menu can't see the anchor-name inside. For component libraries where popups need anchor relationships with their triggers, both must be able to see each other's names in the same tree, or the encapsulation shouldn't split them into two independent shadow roots.

Another list-related point: when a virtual list reuses row nodes and shifts them to new data, the anchor box's geometry changes, and CSS recalculates accordingly — you don't need to manage that. What you do need to manage is whether the menu is still open. If the row is recycled and the menu uses nodes inside that row, the menu will be moved away with the row. Interaction-wise, you should close the popover before the scroll recycling happens. position-visibility: anchors-visible can hide the menu when the anchor leaves the visible area, but it won't reset the popover open state. Call hidePopover() explicitly when scrolling starts so the state stays clean.


6. Canvas and 3D Scenes: The Anchor Can Be a Zero-Size Proxy

Shelf labels and car hotspots in browser 3D have geometry in canvas coordinates, but the labels are DOM because DOM supports selection, keyboard, and accessibility. Anchor Positioning doesn't understand world coordinates. It only understands a CSS box.

So you place a zero-size proxy, have the render loop write the projected screen coordinates into it, and the label anchors to that proxy:

<div class="viewport">
  <canvas></canvas>
  <span class="hotspot" style="anchor-name: --hotspot"></span>
  <div class="label">A-12 · 占用</div>
</div>
.viewport { position: relative; }

.hotspot {
  position: absolute;
  width: 0;
  height: 0;
  left: var(--x);
  top: var(--y);
}

.label {
  position: absolute;
  position-anchor: --hotspot;
  position-area: block-start center;
  position-try-fallbacks: flip-block;
  margin: 0 0 8px 0;
}

The render loop only does one DOM-related thing: write the projected result as --x and --y. Flipping and hiding when out of view remain CSS's job. The proxy must actually occupy a place in layout; display: none and content-visibility skip the subtree and lose the anchor. Use width: 0; height: 0, not display: none.

This pattern's limits are also clear. When projection results change every frame, you're using custom properties to trigger style updates — the anchor relationship no longer saves you from "JS writing coordinates." What it saves is flipping and collision. When hotspot count goes up, the thing to merge is still Canvas text, not a hundred anchor elements. Proxy anchors suit a few clickable, accessible hotspots; they're not for moving the entire particle system into the DOM.


7. A Checklist to Review Before Launch

Let's nail down support to avoid version-number arguments in review:

Capability Chrome / Edge Safari Firefox
anchor-name, anchor(), anchor-size(), @position-try 125 26 147
position-try-fallbacks 128 26 147
position-area (old: inset-area) 129 26 147
anchor-scope 131 26 147
Full set becomes Baseline 2026-01-13, with Firefox 147 and Chrome 144 same same

Newer visibility keywords like anchor-valid and anchor-visible are still not stable across all three engines as of November 2026. In production, use the aligned values anchors-visible and no-overflow, and don't put new keywords into default styles.

Launch checklist:

  1. Each anchor name is unique within its scope; add anchor-scope to list components.
  2. Write position-anchor as an explicit name, don't rely on the initial value.
  3. The positioned element is absolute or fixed and comes after the anchor in source order.
  4. When integrating with Popover, reset inset and the centering margin.
  5. Write position-try-fallbacks when you need flipping; don't try to change arrow direction inside @position-try.
  6. Keep a non-measured static position outside @supports (anchor-name: --a) and (position-area: top).
  7. Call hidePopover() on open menus when the anchor scrolls out of the container, or when virtual rows are recycled.
  8. When traffic on older browsers is still outside the baseline, keep Floating UI as a script for when @supports fails, rather than running both in parallel.

The last point deserves expansion. Detection can go in one pass:

const anchorReady = CSS.supports("anchor-name: --a")
  && CSS.supports("position-area: top")
  && CSS.supports("position-try-fallbacks: flip-block");

If anchorReady is false, then import("floating-ui"). If true, don't also attach autoUpdate. When both write top/left, the later one gets overwritten by the browser's anchor layout in the next frame, resulting in a menu jump. Degradation is a branch, not a superposition.


8. When Not to Use It

Anchor Positioning replaces "DOM box to DOM box" positioning, not the entire floating layer infrastructure.

Keep using Floating UI or equivalent measurement when:

What can safely be left to CSS is also concentrated: design-system tooltips, dropdowns, context menus other than right-click, in-table row popovers, and a few DOM labels following an anchor box. In these cases, removing autoUpdate doesn't remove a feature; it removes a class of listener leaks.


9. Closing Thoughts

Popup positioning dragged on for so long because it looks like a view detail but is actually layout. Measurement-based approaches moved layout onto the main thread, and every scroll listener was a compensation for that fact.

Anchor Positioning gives that compensation back: you declare the anchor and orientation, and the browser handles following and flipping during the layout phase. The Popover API continues to handle top layer, light dismissal, and focus. anchor-scope prevents name collisions between component instances. @supports ensures browsers outside the baseline still get a non-measured position.

If your design system is next year still wrapping a measurement hook around every tooltip, first ask: is the anchor a DOM box? If yes, that JavaScript should now retire.