CSS Anchor Positioning Explainer

CSS Anchor positioning is a CSS feature that allows an element to position and size itself relative to one or more "anchor elements" elsewhere on the page. A typical use case is to "pin" a tooltip to something that triggers it.

This is a short explainer covering the basics of the feature. See also:

The Basics

First, add an anchor-name to the anchor element:

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

Then, use the anchor() function to put another element below the anchor:

.target {
  position: fixed;             /* Must be position: fixed or absolute *
  left: anchor(right);         /* Aligns left edge with anchor's right edge */
  bottom: anchor(top);         /* Aligns bottom edge with anchor's top edge */
  anchor-default: --my-anchor; /* Sets the default target of the anchor() function */
Basic Example
Live Demo Rendered


Fallback Positions

We often want to keep an anchor-positioned element within viewport (if possible), while we don't know the anchor's location in advance or it can be moved by scrolling. This can be achieved by setting a list of fallback positions.

In this example, we will first try to place the target below the anchor, but if that overflows the viewport, then move it above:

.target {
  position: fixed;
  left: anchor(right);
  anchor-default: --my-anchor;
  position-fallback: --top-then-bottom;

@position-fallback --top-then-bottom {
  @try { bottom: anchor(top); }
  @try { top: anchor(bottom); }
Position fallback example
Live Demo Rendered

Note: Setting position: absolute will keep the element within its containing block instead of the viewport.

Using Multiple Anchor Elements

The anchor() and anchor-size() functions can optionally take an anchor name parameter, so that they are solved against the provided anchor instead of the default anchor. This allows us to anchor to multiple elements and create more complicated layout.

In this example (stolen from Jhey Tompkins), we create min and max value indicators in a bar chart:

.max-indicator {
  position: fixed;
  left: anchor(--chart right);
  bottom: max(
    anchor(--anchor-1 top),
    anchor(--anchor-2 top),
    anchor(--anchor-3 top)
Bar chart calc
Live Demo Rendered

Note: If anchor-default is not set and scrolling is relevant, we need to set the anchor-scroll property to specify which anchor to should scroll with.