One Element, Many Anchors

The CSS anchor positioning spec is still young and changing, but it already supports something JavaScript developers have long taken for granted: a single element pinned to more than one reference point on the page. The trick is to declare each anchor relationship on a different inset property.

<div class="anchor-1"></div>
<div class="anchor-2"></div>
<div class="target"></div>

After registering the anchors with anchor-name, you have two ways to attach a target. The position-anchor property is the straightforward route — it establishes a target-anchor relationship, but it only accepts a single anchor.

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

That’s where the anchor() function comes in. It also takes one anchor per declaration, but nothing stops you from using it on multiple inset properties, each time referencing a different anchor name. The second argument of anchor() is the edge you position against — physical or logical values like top, bottom, start, end, inside, or outside — or a percentage.

In practice, that means you can attach the target’s top edge to one anchor’s bottom edge, and the target’s left edge to that same anchor’s right edge.

.target {
  top: anchor(--anchor-1, bottom);
}

The same pattern applies to the other inset properties:

.target {
  top: anchor(--anchor-1 bottom);
  left: anchor(--anchor-1 right);
  bottom: anchor(--anchor-2 top);
  right: anchor(--anchor-2 left);
}

But declaring insets is not enough. The target needs to be yanked out of normal document flow with absolute positioning for the inset values to take effect.

.target {
  position: absolute;

  top: anchor(--anchor-1 bottom);
  left: anchor(--anchor-1 right);
  bottom: anchor(--anchor-2 top);
  right: anchor(--anchor-2 left);
}

Two Anchors in Action

The demo pairs the target with two <textarea> elements, which is clever because a textarea is resizable by dragging. The two textareas are absolutely positioned: one pinned to the viewport’s top-left, the other to the bottom-right.

Attach the target’s top and left edges to the first textarea’s bottom and right edges. Then attach the target’s bottom and right edges to the second textarea’s top and left edges. The target becomes stretched between the two textareas, so resizing them stretches the target in response.

One catch: a textarea resizes from its bottom-right corner. The second textarea is positioned such that its resizer isn’t directly next to the target. Spinning it with rotate(180deg) puts everything in the right place.

A simple background-color on the target is enough to visualize the effect; Chris’s demo drops in a background-image character for flair. The whole thing still requires a Chromium browser, but the fact that CSS alone can manage multiple anchor points — without a line of JavaScript — is the kind of conceptual demo that sticks.