Ga naar hoofdinhoud

Monday Snack: CSS Anchor Positioning

by Carl — May 18, 2026
2 minutes

If you’ve ever struggled to keep a popup, dropdown, or tooltip perfectly aligned with an element while a user scrolls, you are definitely not alone. I used to do this the hard way, too.

For a long time, handling overlays required a choice: either pull in a heavy external positioning library or write custom JavaScript to manually calculate coordinates using getBoundingClientRect(). It often felt like no matter how much defensive code you wrote, a nested scroll container or a mobile screen resize would find a way to break the layout.

We shouldn't need complex math just to anchor an element to another element.

The Native Solution

The native CSS Anchor Positioning API solves this problem cleanly. Instead of relying on JavaScript event listeners to constantly recalculate coordinates, the browser handles the tethering natively. This approach is highly performant, cuts out significant boilerplate, and works entirely within your CSS.

Here is how you can set it up in two straightforward steps: Name the anchor, and target the anchor.


Implementation

1. Define the Anchor Element

First, identify the element you want to tether things to (like a button) and give it a unique name using the anchor-name property. The name must start with a double dash (--), matching the syntax of a CSS custom property.

<button class="action-btn">Click Me</button>
html
.action-btn {
  /* Define the anchor name */
  anchor-name: --my-button;
}
css

2. Style the Positioned Element

Next, style the element that will float next to your anchor. It needs a position of absolute or fixed. You then use position-anchor to connect it to the named anchor you just created.

<div class="my-tooltip">I'm a native tooltip!</div>
html
.my-tooltip {
  position: absolute;
  
  /* Connect to the button anchor */
  position-anchor: --my-button;
  
  /* Place the top of the tooltip at the bottom of the button */
  top: anchor(bottom);
  
  /* Align the horizontal centers */
  left: anchor(center);
  transform: translateX(-50%); 
}
css

Implicit vs. Explicit Anchoring

If you are managing a complex view with multiple anchors on a single page, you can bypass position-anchor entirely by explicitly naming the anchor directly inside the positioning functions:

.my-tooltip {
  position: absolute;

  /* Explicitly naming the anchor inside each function */
  top: anchor(--my-button bottom);
  left: anchor(--my-button center);
}
css

Using position-anchor is usually the cleaner approach. It acts as a scoped default for the element, meaning you don't have to keep repeating --my-button inside every single anchor() call.

Adopting this API lets you offload layout tracking to the browser, making your UI components lighter and much easier to maintain.


Sources: