CSS Anchor Positioning Overview

Positioning an Element Relative to Another, the Old Way

Placing a tooltip or dropdown menu precisely next to a specific button - and having it intelligently flip position if it would otherwise overflow the screen - has traditionally required a JavaScript positioning library that measures both elements and calculates coordinates manually.

Step 1: Declare an Anchor

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

Any element can be marked as an anchor by giving it a custom anchor name, similar in spirit to a custom property name.

Step 2: Position Another Element Relative to It

.tooltip {
  position: absolute;
  position-anchor: --my-button;
  top: anchor(bottom);
  left: anchor(center);
}

The anchor() function reads a specific edge or point of the anchor element - here, positioning the tooltip just below the button's bottom edge, horizontally centered on it - without any JavaScript measuring involved.

Automatic Fallback Positioning

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

position-try-fallbacks lets a positioned element automatically try an alternative placement - such as flipping to appear above the anchor instead of below - if the preferred position would overflow the viewport, a common requirement for tooltips and dropdown menus near the edge of the screen.

Why This Is a Meaningful Change

Anchor positioning moves a whole category of positioning logic - previously requiring a JavaScript library - directly into native CSS, reducing the amount of script needed to build things like tooltips, popovers and dropdown menus that must stay attached to a trigger element.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.