2 min read

CSS Anchor Positioning API

The CSS Anchor Positioning API allows you to tether an absolutely positioned element (like a tooltip, popover, or dropdown menu) to one or more "anchor" elements on the page. This solves the long-standing problem of positioning floating elements relative to other elements without using JavaScript libraries like Popper.js.

1. The Concept

You define an anchor element (the trigger) and a positioned element (the popup). The positioned element is then tethered to the anchor using CSS properties.

2. Defining an Anchor

You can define an anchor in two ways:

Implicit Anchor (HTML Attribute)

Using the anchor attribute on the positioned element to point to the ID of the anchor element.

<button id="my-button">Click me</button>
<div class="tooltip" anchor="my-button">I am a tooltip</div>

Explicit Anchor (CSS Property)

Using the anchor-name property on the anchor element.

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

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

3. Positioning the Element

Once anchored, you use the anchor() function within standard positioning properties (top, left, right, bottom, etc.) to align the element.

.tooltip {
  position: absolute;

  /* Align the top of the tooltip to the bottom of the anchor */
  top: anchor(bottom);

  /* Align the left of the tooltip to the left of the anchor */
  left: anchor(left);
}

anchor() Arguments

  • anchor(side): Refers to the position of the anchor's side (top, right, bottom, left, center, etc.).
  • anchor(--name side): Refers to a specific named anchor.

4. Centering

To center a tooltip horizontally relative to the anchor:

.tooltip {
  position: absolute;
  top: anchor(bottom);
  left: anchor(center);
  transform: translateX(-50%); /* Standard centering technique */
}

5. Fallback Positioning (@position-try)

If the tooltip goes off-screen, you can define fallback positions using @position-try.

@position-try --flip-bottom {
  top: anchor(bottom);
}

.tooltip {
  position-try-fallbacks: --flip-bottom, flip-block;
}

programming/css/css programming/css/positioning programming/javascript/vanilla/dom-manipulation