使用 CSS anchor positioning 的 Follow-the-leader pattern
There’s a pattern I’ve been implementing lately that creates a little “follow-the-leader” effect using anchor positioning. And the technique is pretty neat too. It involves creating a single “follower” (positioned) element and dynamically updating it’s anchor on an event or state change. This could be in JavaScript (i.e. on click), or in CSS directly (i.e. on hover, focus/focus-within, updating the current-target, etc).
最近我一直在实现一种模式,它使用 anchor positioning 创建一种小的“follow-the-leader”效果。而且这个技巧非常巧妙。它涉及创建一个单一的“follower”(positioned)元素,并在事件或状态变化时动态更新它的 anchor。这可以在 JavaScript 中实现(例如点击时),或者直接在 CSS 中(例如 hover、focus/focus-within、更新 current-target 等)。
Note: This technique is demonstrated using the CSS anchor positioning API, which is a part of Interop 2025. At the time of this writing, it has shipped in Chromium and is planned to ship soon in Webkit. I will update this post as browser support rolls out.
注意: 此技术使用 CSS anchor positioning API 进行演示,这是 Interop 2025 的一部分。目前为止,它已在 Chromium 中发布,并计划很快在 Webkit 中发布。我会随着浏览器支持的推出而更新这篇文章。
The Technique
该技巧
Let’s start with the most basic “event” for demo purposes: hover.
为了演示目的,让我们从最基本的“event”开始:hover。
Randomize widths
随机化宽度
Hover over these cards if you're on Chrome 125+ or Safari 26+.
如果你在使用 Chrome 125+ 或 Safari 26+,请将鼠标悬停在这些卡片上。
You have one follower (👀) which has a position-anchor set to a specific name (in this case it’s --hovered). For each of the “possible anchors”, you update the anchor-name to be --hovered. This is how you get it to change anchors and reposition itself.
你有一个跟随者(👀),它有一个设置为特定名称的 position-anchor(在本例中是 --hovered)。对于每一个“可能的锚点”,你将 anchor-name 更新为 --hovered。这就是让它切换锚点并重新定位自己的方式。
.follower {
/* anchor the follower element */
position: fixed;
position-anchor: --hovered;
}
.possible-anchor:hover {
/* update the active anchor */
anchor-name: --hovered;
}
You also probably want it to smoothly animate between anchors, which can be done with a basic transition:
你可能还希望它在锚点之间平滑动画,这可以通过基本的 transition 实现:
.follower {
/* transition the animation */
transition: top 0.5s ease;
/...