The Major Pitfall of Anchor Positioning – Frontend Masters Blog

The Major Pitfall of Anchor Positioning – Frontend Masters Blog

3 Min Read

Alternate Titles:

– “Something’s Rotten in The Consortium”
– “It’s Batpoop Crazy Easy To Break Anchors”

I feel foolish because I’ve often touted one of the amazing benefits of Anchor Positioning in CSS: the ability to position elements relative to others regardless of their DOM placement. However, this assumption is incorrect. There are many initially perplexing limitations with anchor positioning that don’t have precedents in CSS.

Here’s a little rant about it:

I’m being intentionally dramatic because I genuinely believe the CSS authorities should address this issue. I’m sure there are reasons for its current behavior, likely including performance, but its current state makes it too easy to make mistakes. A “second pass” in the CSS mechanism might help locate anchors more reliably.

If you’re logged into CodePen, open this demo and rearrange the DOM positions as shown in the video to witness the issue.

It’s Fixable.

It’s somewhat complex to suggest moving the tooltip before the anchor, but it’s indicative of the limitations in DOM placement expectations.

Temani Afif has a good article about this, echoing a crucial point:

The anchor element must be fully laid out before the element anchored to it.

Thus, consideration of the position value is crucial. The anchored element is almost certainly positioned absolutely, with concerns primarily about the anchor itself. If they are siblings and the anchor has a non-default position, it must come first. If the anchor is elsewhere or a parent, ensure they share the same “containing block” or the anchor parent defaults to static positioning. Temani provides a detailed explanation of this.

James Stuckey Weber also offers insights on this matter, with specific advice:

For optimal anchor positioning, ensure:

1. The anchor and positioned element are siblings.
2. The anchor appears first in the DOM.

This advice is straightforward and teachable, yet it’s troubling. CSS has introduced a peculiar problem that feels unprecedented and unwelcome for troubleshooting. I hope CSS resolves this issue moving forward.

If you’re still confused after establishing a working anchor:

1. Anchor-tool is a useful resource for understanding the “span” concept, which can be challenging to grasp.

2. The anchoring area functions similarly to a grid cell, allowing alignment and justification inside. The “cell” is called the Inset-Modified Containing Block (IMCB), as explained well by Bramus. The inset part involves resizing by pushing against the cell walls. Curious enough, IMCB is very close to ICBM, both potentially causing disruption.

You might also like