CSS: Anchor Positioning

By Xah Lee. Date: .
xtodo

css anchor_positioning

ai generated

CSS Anchor Positioning is a modern CSS feature that lets you position one element relative to another element (the "anchor") purely with CSS — no JavaScript needed.

It’s especially useful for:

Core Idea

You mark one element as the anchor, then tell another element (usually position: absolute) to position itself based on the anchor’s edges, center, or size.

Basic Syntax (2026 standard)

/* 1. Define the anchor */
.anchor {
  anchor-name: --my-tooltip;   /* must start with -- */
}

/* 2. Position the element relative to it */
.tooltip {
  position: absolute;
  position-anchor: --my-tooltip;   /* link to the anchor */

  /* Position it (two main ways): */

  /* Way A: Using anchor() function */
  top: anchor(bottom);      /* top of tooltip = bottom of anchor */
  left: anchor(left);

  /* Way B: Simpler shorthand with position-area */
  position-area: top center;   /* places it above and centered */
}

Main Properties & Functions

Feature Purpose Example
anchor-name: --name Defines an element as an anchor --my-button
position-anchor Links the positioned element to an anchor --my-button
anchor() function References specific sides of the anchor bottom: anchor(top)
position-area Easy 9-zone positioning (like a grid) position-area: top right
position-try / position-try-fallbacks Automatic flip when it overflows screen position-try: flip-block

Simple Real-World Example

<button class="anchor">Hover me</button>
<div class="tooltip">I'm a tooltip!</div>
.anchor {
  anchor-name: --btn;
}

.tooltip {
  position: absolute;
  position-anchor: --btn;
  position-area: top center;   /* auto places above + centered */
  margin-bottom: 8px;          /* small gap */
  background: #333;
  color: white;
  padding: 8px 12px;
}

Why It’s a Big Deal

Before anchor positioning, you had to use JavaScript to:

Now it’s all native, performant, and handles scrolling/overflow automatically in most cases.

Would you like a full working demo (e.g. tooltip, dropdown, or popover with fallback positions)? Just tell me what you want to build.