弹层尺寸我配了五年,现在 CSS 自己会量了——anchor-size() 把相对尺寸这件事彻底原生化了

我配了五年 tooltip,今天终于把弹层尺寸这件事彻底想清楚了——以前每次都要靠 JS 去读锚元素的 offsetWidth/offsetHeight,再算来算去配 max-width;现在浏览器自己会量了,一行 CSS 搞定。

Chrome 125 开始,anchor-size() 这个函数把弹层尺寸的计算彻底还给了 CSS。

以前怎么做的

假设你有一个按钮(锚点),点它弹出一个下拉菜单。菜单的宽度要等于按钮宽度,高度要跟着内容走但不能超过某个最大值:

const btn = document.querySelector('.trigger');
const menu = document.querySelector('.menu');

btn.addEventListener('click', () => {
  // 读按钮尺寸
  const w = btn.offsetWidth;
  menu.style.width = w + 'px';
  // 再算一堆边距和偏移
});

这还算简单的。如果菜单要跟随滚动、响应式布局、RTL 方向,JS 代码就膨胀了。

anchor-size() 怎么用

现在你只需要给锚点起个名字,然后在弹层里直接引用它的尺寸:

/* 1. 给锚点元素命名 */
.trigger {
  anchor-name: --my-trigger;
}

/* 2. 弹层引用锚点的宽度作为自己的宽度 */
.dropdown {
  position-anchor: --my-trigger;
  width: anchor-size(width);
  max-height: anchor-size(height, 300px); /* 备选值 */
}

就这么简单。anchor-size(width) 告诉浏览器「拿锚点元素的宽度」,anchor-size(height, 300px) 表示「没有锚点时用 300px 做备选」。

这几个参数到底怎么选

anchor-size() 接受三个参数,第三个是备选值省略时会导致声明失效:

  • anchor-size(width) — 锚点的 content box 宽度
  • anchor-size(height) — 锚点的 content box 高度
  • anchor-size(block) — 锚点 containing block 在块轴上的长度
  • anchor-size(inline) — 锚点 containing block 在行轴上的长度
  • anchor-size(self-block) — 锚点自身在块轴上的长度
  • anchor-size(self-inline) — 锚点自身在行轴上的长度

实战中最常用的组合:

/* 弹层宽度等于锚点宽度,最小 200px,最大 400px */
.dropdown {
  width: anchor-size(width, 100%);
  min-width: 200px;
  max-width: 400px;
}

/* 用锚点宽度减去固定边距,实现「比锚点略宽」的常见需求 */
.card {
  width: calc(anchor-size(width) - 32px);
}

/* RTL 场景下,锚点高度决定弹层最大高度 */
.popover {
  position-anchor: --my-trigger;
  max-height: anchor-size(height, 400px);
  overflow-y: auto;
}

完整实战:Tooltip 跟随锚点

<button class="trigger" anchor="--tip-trigger">hover me</button>

<div class="tooltip" role="tooltip">
  这是提示文字,内容可长可短
</div>
.tooltip {
  position-anchor: --tip-trigger;

  /* 宽高都跟锚点走 */
  width: anchor-size(width);
  height: anchor-size(height, auto);

  /* 位置用 anchor() 定位 */
  position: absolute;
  left: anchor(bottom);
  top: anchor(--tip-trigger top);

  /* 备选值防锚点丢失 */
  min-width: 100px;
  max-width: 300px;
}

兼容性:不是所有浏览器都支持

Chrome 125+ 和 Edge 125+ 已经支持,Safari 暂未支持,Firefox 在测试中。生产环境建议用 @supports 做渐进增强:

.tooltip {
  /* 不支持的浏览器走 JS 方案 */
  width: 200px;
}

@supports (width: anchor-size(width)) {
  .tooltip {
    width: anchor-size(width, 100%);
  }
}

下一步

anchor-size() 和 anchor() 是配套的——前者管尺寸,后者管位置。加上 @position-try 处理屏幕边缘碰撞,@container style() 做状态查询,这四个 API 组合起来,一个完整的弹层系统就不需要任何 JS 坐标计算了。

下一步:打开 Chrome DevTools 试试 anchor-size(width) 在真实项目里的效果,配上 @supports 渐进增强,生产可用。

评论区

0 条评论

登录后可评论。

小鹿·界面实验室 1770 阅读