YL

MODERN CSS

锚点定位Anchor Positioning

让 tooltip / 下拉 / 气泡自动贴住触发元素,还能在空间不足时自动翻转方向。以前必须用 Popper/Floating UI 这类 JS 库。

效果预览

悬停看气泡
锚点定位气泡用 anchor-name 自动贴住按钮,空间不足会翻到另一侧。

适合用在哪

Tooltip、下拉菜单、选择器弹层、Popover 的定位。尤其是靠近视口边缘时的自动避让。

容易踩的坑

  • 同一页多个触发器共用一个 anchor-name,浮层全部贴到最后一个锚点上。
  • 浮层与锚点不在同一包含块或被 overflow 裁剪,定位看似失效难以排查。
  • 只写主位置不配 position-try-fallbacks,靠近视口边缘时浮层仍被截断。

设计提示词 · Prompt

锚点定位(CSS Anchor Positioning):给触发元素设 anchor-name: --my-btn;给浮层设 position:absolute; position-anchor: --my-btn; 然后用 position-area(如 top、bottom span-right)或 anchor() 函数指定相对锚点的位置,例如 left: anchor(--my-btn left)。空间不足时浏览器会自动把浮层翻到另一侧(position-try-fallbacks 可自定义备选位置序列)。配套还有 @position-try 定义备选定位规则。当前支持度:Chrome 125+、Safari 26+;Firefox 仍在实现中,生产环境建议先用 @supports (anchor-name: --x) 判断,不支持时回退到 Floating UI。
Anchor Positioning: give the trigger element anchor-name: --my-btn; give the floating element position:absolute; position-anchor: --my-btn; then use position-area (e.g. top, bottom span-right) or the anchor() function to place it relative to the anchor, e.g. left: anchor(--my-btn left). When space runs out, the browser automatically flips the floating element to the other side (position-try-fallbacks lets you customize the fallback sequence). There's also @position-try for defining fallback positioning rules. Current support: Chrome 125+, Safari 26+; Firefox is still implementing it, so in production check with @supports (anchor-name: --x) first and fall back to Floating UI when unsupported.

常见搭配

同一页面里经常和「锚点定位」一起出现的模式,可以收藏后用「组合收藏为整页提示词」一起交给 AI。

演示 HTML 结构

<div class="s" style="width:100%">
  <div class="mc-anchor">
    <span class="mc-anchor__btn">悬停看气泡</span>
    <div class="mc-anchor__tip"><b>锚点定位</b>气泡用 anchor-name 自动贴住按钮,空间不足会翻到另一侧。</div>
  </div>
</div>

标签