CSS anchor() Function

The anchor() function allows you to position an element relative to a specific anchor element.

The anchor() function is a core part of the CSS Anchor Positioning API. By linking an absolutely positioned element to a target anchor, you can create tooltips, popovers, and dropdown menus that stay perfectly aligned with their trigger elements, even as the page layout changes or resizes.

To use it, you first define an anchor element using the anchor-name property. Then, on your absolutely positioned element, you use the anchor() function within inset properties (like top, bottom, left, or right) to bind its edges to the corresponding sides of the anchor.

Here is a basic example showing a tooltip positioned directly below an anchor element:

View Output Full Screen Preview

How It Works

The anchor() function resolves to a length value. It takes two main arguments: the name of the anchor you want to reference, and the side of the anchor you want to align to.

For example, top: anchor(--my-anchor bottom) tells the browser to set the top edge of the positioned element to exactly match the bottom edge of the element named --my-anchor.

You can also omit the anchor name if you have linked the elements using the position-anchor property. In that case, you only need to specify the side, like anchor(bottom).

Providing a Fallback

You can provide an optional fallback value as the final argument in the anchor() function. If the referenced anchor does not exist (for example, if it was removed from the DOM or has display: none), the browser will use the fallback value instead.

For example: top: anchor(--my-anchor bottom, 50px).

Official Syntax

The official syntax of the anchor() function is as follows:

Possible Values

As indicated in the official syntax, the anchor() function accepts the following values:

anchor-name

An optional dashed-ident (e.g., --my-anchor) that matches the anchor-name property of the target element. If omitted, it defaults to the element specified by the position-anchor property.

anchor-side

Specifies which side of the anchor element to reference. Possible values include:

  • Physical sides: top, bottom, left, right
  • Logical sides: start, end, self-start, self-end
  • Center alignment: center
  • Percentages: e.g., 50%
length-percentage

An optional fallback length or percentage value to use if the anchor element cannot be resolved.

CSS Specifications

Browser Support

The following table provided by Caniuse.com shows the level of browser support for this feature.