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

弹层宽度跟按钮一样宽、下拉框高度跟输入框一样高——这类「相对尺寸」需求,前端写了五年,全靠 JS 算。

现在 CSS 自己会量了。

anchor-size() 是什么

CSS 锚点定位(Anchor Positioning)里有个函数叫 anchor-size(),它的作用很简单:让一个元素的尺寸等于某个锚点元素的尺寸。

/* 弹层宽度等于锚点按钮的宽度 */
.popover {
  width: anchor-size(width);
}

/* 带备用值:没有锚点时默认 200px */
.tooltip {
  width: anchor-size(--trigger width, 200px);
}

/* 高度也同理,锚点是谁告诉 CSS 就行 */
.dropdown {
  block-size: anchor-size(--anchor block, auto);
}

锚点怎么指定?靠 anchor-name:

.trigger {
  anchor-name: --my-trigger;
}

.popover {
  position-anchor: --my-trigger;
  width: anchor-size(width);
}

这就是 CSS 原生版的「相对尺寸」——不用 JS、浏览器自己算。

配合 scroll-driven animation:尺寸变时间线

anchor-size() 本身是静态的,但当它遇上 scroll-driven animations,就有意思了。

一个常见场景:滚动时弹层高度跟着锚点内容动态变化,同时弹层内部元素要根据这个高度做进度动画。

/* 定义锚点和弹层 */
.card {
  anchor-name: --card;
}

.expanded-panel {
  position-anchor: --card;
  height: anchor-size(--card block);  /* 高度跟随锚点 */

  /* 滚动驱动动画:高度变化驱动内部进度条 */
  animation: grow-panel linear;
  animation-timeline: scroll();
}

@keyframes grow-panel {
  from { --progress: 0; }
  to   { --progress: 1; }
}

更实用的例子:锚点尺寸驱动视差滚动。

.card-image {
  anchor-name: --img;
}

.card-content {
  position-anchor: --img;
  /* 内容区高度 = 图片高度 */
  block-size: anchor-size(--img block);

  /* 视差动画:滚动时内容跟随图片缩放 */
  animation: parallax-slide linear both;
  animation-timeline: scroll();
  animation-range: entry 0% cover 100%;
}

@keyframes parallax-slide {
  from { transform: translateY(20px); opacity: 0; }
  to   { transform: translateY(0); opacity: 1; }
}

三种 anchor-size 组合场景

1. 宽度跟随

弹层宽度 = 触发器宽度,最常见的相对尺寸场景。

.context-menu {
  width: anchor-size(--btn width);
}

2. 高度跟随(动态内容)

锚点内容可能是动态高度的——比如一行、两行、三行文字。弹层高度跟着变。

.dropdown-panel {
  block-size: anchor-size(--menu-item self-block);
}

3. 间距相对化

不只是尺寸,间距也可以用 anchor 尺寸来算。

.floating-label {
  /* 标签间距 = 锚点宽度的一半 */
  margin-left: calc(anchor-size(--input width) / 2);
}

浏览器支持情况

anchor-size() 属于 CSS Anchor Positioning 模块,Chrome 125+ 已支持,Safari 暂未支持。

/* 降级处理 */
@supports (anchor-size: width) {
  .popover { width: anchor-size(--btn width); }
}
@supports not (anchor-size: width) {
  .popover { width: 200px; }  /* JS 兜底 */
}

落地步骤

  1. 先给触发元素加 anchor-name
  2. 给弹层加 position-anchor(指向同一名字)
  3. 用 anchor-size(width) 或 anchor-size(block) 取尺寸
  4. 配合 scroll-driven animation 做联动效果
  5. @supports 写降级

相对尺寸这个需求存在了多少年,JS 就写了多少年。现在 CSS 自己会量了——不需要你算,浏览器自己知道该是多少。

评论区

0 条评论

登录后可评论。

小鹿·界面实验室 2339 阅读