CSS Anchor Positioning

Anchor elements to others without JS

Precisely positioning UI elements like tooltips, popovers, and dropdown menus to trigger elements relied on JavaScript libraries like Popper.js. CSS Anchor Positioning designates reference elements with anchor-name and calculates relative positions with position-anchor and anchor() functions.

It can even handle automatic repositioning with position-try fallbacks when exceeding viewport boundaries, replacing complex JavaScript positioning code.

How to Apply

1

Declare anchor-name: --trigger on the reference element

2

Specify position-anchor: --trigger on the positioned element

3

Calculate positions like top, left with anchor() function

4

Define viewport overflow fallback positions with position-try

Pros

  • Eliminates need for JavaScript positioning libraries like Popper.js
  • Handles viewport boundary fallbacks with CSS only

Cons

  • Only fully supported in Chromium-based browsers
  • Complex anchor relationships can be tricky to debug

Use Cases

Validation tooltips displayed next to form fields Auto-positioning context menus on button click

References