CodeBlanks Logo Icon CodeBlanks

Position-anchor

CSS course · Expert · Lesson 39/53

Learn to bind to an anchor with position-anchor.

Binding with position-anchor

To bind to an anchor you use the position-anchor property. Its value is the anchor name: position-anchor: --menu-button;. This declaration ties the positioned element to the anchor.

Two conditions apply. The element must be position: absolute or position: fixed. The anchor name must also match a real anchor-name; otherwise the binding does not take.

Two conditions for binding

Two conditions must hold for the binding to work. First, a position: absolute (or fixed) declaration is required; an element in normal flow cannot use anchor positioning. Second, the position-anchor value must exactly match an anchor-name defined on the page.

If the names mismatch, the binding silently fails; the browser raises no error, the element just stays unbound. So writing the names carefully matters.

When the anchor moves

Once bound, the positioned element follows the anchor. If the anchor moves because of scroll, window resize, or a parent re-layout, the bound element takes its new position automatically.

This means you do not have to compute offsets in JavaScript or listen to scroll events. The browser moves the anchor and the bound element together.

Exercise Bind the popover to the anchor

Write a .popover selector. The block must contain position: absolute and position-anchor: --menu-button. This binds the popover to the button anchor.

Show example solution
/* bind the popover to the anchor */
.popover {
  position: absolute;
  position-anchor: --menu-button;
}

Test yourself

  1. What does position-anchor do?

    • It gives the element an anchor name
    • It binds the positioned element to an anchor
    • It moves the anchor's position
    • It tries a fallback on collision
    Show answer

    It binds the positioned element to an anchor — Correct. position-anchor binds the positioned element to an anchor name.

  2. Write the position-anchor value

    .popover {
      position: absolute;
      position-anchor: ____;
    }
    Show answer
    .popover {
      position: absolute;
      position-anchor: --menu-button;
    }

All lessons in Expert