锚点名称

Avatar of Geoff Graham
Geoff Graham

DigitalOcean 为您的旅程各个阶段提供云产品。立即开始使用 $200 的免费额度!

在元素上声明 CSS anchor-name 属性会将其注册为一个“锚点”,我们可以将其用作定位其他元素的参考点。

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

该属性是 CSS 锚点定位 的一部分,它是一组用于将一个元素的位置链接到另一个元素的功能,这些功能旨在一起使用。

语法

anchor-name: none | <dashed-ident>#
  • 初始值: none
  • 应用于: 生成 主框 的所有元素
  • 继承:
  • 百分比: 不适用
  • 计算值: 按提供的值
  • 规范顺序: 按语法
  • 动画: 离散

属性值

/* Keyword values */
anchor-name: none;

/* <dashed-ident> examples */
anchor-name: --anchor;
anchor-name: --my-anchor;
anchor-name: --myAnchor;
  • none: 从应用于它的元素中移除锚点定位。换句话说,其他元素无法相对于它进行定位。
  • <dashed-ident>: 用于标识元素的自定义名称,旨在用作锚点,类似于 <custom-ident>,它以声明方式标识它并将它与其他锚点区分开来。该值被称为“虚线”标识符,因为它必须以两个破折号(--)为前缀,就像我们对 CSS 自定义属性 所做的那样,例如 --my-anchor

基本用法

一旦我们将元素注册为锚点,我们就可以在另一个元素上引用它,并将该元素相对于锚点的位置进行定位。因此,这将我们选择的“目标”元素与我们刚定义的锚点相关联。

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

.target {
  position-anchor: --my-anchor;
}

但在我们这样做之前,必须给 .target 绝对定位,以将其从正常的文档流中取出。

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

.target {
  position: absolute;
  position-anchor: --my-anchor;
}

有了这个,我们就可以开始定位 .target 了。现在,它的位置相对于 .anchor 元素的流。因此,例如,我们可以使用 anchor() 函数将 .target 相对于 .anchor 的底边进行定位。

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

.target {
  position: absolute;
  position-anchor: --my-anchor;
  top: anchor(bottom);
}

这就像是在说,“我想将元素的顶部沿另一个元素的底边进行定位。”结果是 .target 位于 .anchor 的下方。

Two boxes stacked vertically, the top one labeled anchor and the bottom one labeled target.

如果我们要改成 .anchor 的顶边。

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

.target {
  position: absolute;
  position-anchor: --my-anchor;
  bottom: anchor(top);
}
Two boxes stacked vertically, the top one labeled target and the bottom one labeled anchor.

引用锚点名称

我们刚刚看到了如何通过在要锚定的元素上声明 anchor-name 来注册一个“锚点”,然后通过使用 position-anchor 属性在目标元素上引用 anchor-name 来将某个“目标”元素与该锚点关联。

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

.target {
  position-anchor: --my-anchor;
}

将目标与锚点关联的另一种方法是在 anchor() 函数中直接引用 anchor-name

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

.target {
  top: anchor(--my-anchor end);
}

这是一种减少代码量的好方法,因为我们可以在单个声明中引用锚点以及我们希望如何将目标定位到它。

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

.target {
  top: anchor(--my-anchor end);

  /* Same as: */
  position-anchor: --my-anchor;
  top: anchor(end);
}

引用多个锚点名称

是的,我们可以将一个目标元素链接到多个不同的锚点。

.target {
  position: absolute;
  top: anchor(--anchor-1 bottom);
  bottom: anchor(--anchor-2 top);
  left: anchor(--anchor-3 right);
  right: anbchor(--anchor-4 left);
}

这可能不是世界上最好的主意,因为它实际上跨越了目标在页面上的多个其他元素的位置,使其能够采用不同的尺寸和形状。

规范

anchor-name 属性定义在 CSS 锚点定位模块级别 1 规范 中,该规范在撰写本文时处于工作草案阶段。这意味着从现在到该功能成为正式候选推荐以供实施之前,可能会有很多变化。

浏览器支持

Data on support for the css-anchor-positioning feature across the major browsers from caniuse.com

更多信息和教程