Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

anchor-name: name a box that another element can follow

Connect a positioned element to an eligible anchor without copying coordinates into JavaScript.

Version: CSS Modules

Syntax

anchor-name: --target;

anchor-name assigns one or more dashed identifiers to an element’s principal box, for example --target or a comma-separated list. none assigns no names. It does not itself move the anchor, create a popup or establish keyboard behavior. A positioned element can select the name through position-anchor and use anchor() to obtain an edge of the target box.

Names need not be unique. The selected target depends on scope, DOM relationships and whether a candidate is an acceptable anchor that can be laid out in time. Reusable components should deliberately manage this scope instead of treating names like globally unique HTML IDs. An element without a suitable box cannot supply ordinary anchor geometry. Include fallbacks and verify the complete positioning syntax, not only recognition of anchor-name.

The example gives an 80×30px anchor the name --target at left 40px and top 20px. A second box follows its left and bottom edges, appearing at 40,50. Moving the anchor to 100,50 moves the dependent box to 100,80 without JavaScript calculating its position. Renaming the anchor to --other breaks the lookup, so the explicit 0px fallbacks place the dependent box at 0,0. JavaScript only changes styles and reads the resulting geometry.

Examples

const host = document.createElement('div');
host.style.cssText = 'position:relative;width:500px;height:200px';
const anchor = document.createElement('div'), popup = document.createElement('div');
anchor.style.cssText = 'position:absolute;left:40px;top:20px;width:80px;height:30px;anchor-name:--target';
popup.style.cssText = 'position:absolute;position-anchor:--target;left:anchor(left,0px);top:anchor(bottom,0px);width:50px;height:20px';
host.append(anchor,popup); document.body.append(host);
const position = () => {const a=host.getBoundingClientRect(),b=popup.getBoundingClientRect();return [Math.round(b.left-a.left),Math.round(b.top-a.top)].join(' ');};
console.log('anchored:', position());
anchor.style.left='100px'; anchor.style.top='50px';
console.log('moved:', position());
anchor.style.anchorName='--other';
console.log('missing name:', position());
host.remove();

Result

anchored: 40 50
moved: 100 80
missing name: 0 0

Executed in Chromium 157.0.8103.51 in one isolated containing block. Anchor positioning is newer CSS: test target browsers and provide a usable fallback. Name resolution across shadow trees, automatic overflow alternatives and accessible popup interactions are outside this example.

Sources