Sub topic 3
Placing an element with anchor()
This chapter assumes you know the position property (relative, absolute, fixed) and inset properties such as top and left. It also assumes you know what a containing block is. You should have declared an anchor with anchor-name and linked an element to it with position-anchor, as covered in the previous chapter. Here you will use the anchor() function to place an element against the edges of that anchor.
What anchor() does
anchor() is a CSS function that returns a length. The length is the position of one edge (or the center) of an anchor element. You use it as the value of an inset property, so the browser can turn "the top of that button" into the number of pixels top, left, bottom or right needs.
Here is a complete tooltip that sits above its trigger:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>anchor() tooltip</title>
<style>
.trigger {
anchor-name: --tip;
}
.tooltip {
position: absolute;
position-anchor: --tip;
bottom: anchor(top);
left: anchor(center);
translate: -50% 0;
margin-bottom: 8px;
}
</style>
</head>
<body>
<button class="trigger" aria-describedby="tip-text">Save</button>
<div class="tooltip" id="tip-text" role="tooltip">Saves your draft</div>
</body>
</html>The trigger is declared as the anchor --tip. The tooltip is absolutely positioned and linked to that anchor. Two things then happen:
bottom: anchor(top)puts the tooltip's bottom edge at the anchor's top edge.left: anchor(center)puts the tooltip's left edge at the anchor's horizontal center.
The tooltip's left edge is now at the center of the button, so the tooltip sits too far right. translate: -50% 0 shifts it back by half its own width, which centers it. margin-bottom: 8px opens a gap between the tooltip and the button.
The anchor() function does not move anything by itself. It supplies a number to an inset property. The element is still an ordinary absolutely positioned box.
The syntax
The general form is:
anchor(<anchor-name>? <anchor-side>, <fallback>?)<anchor-name>is optional. It is a dashed identifier such as--tip. If you leave it out, the function uses the anchor named by the element'sposition-anchor.<anchor-side>is required. It says which edge, or the center, you want.<fallback>is optional. It is a length or percentage used when the function cannot resolve.
All of these are valid:
.a { top: anchor(bottom); }
.b { top: anchor(--other bottom); }
.c { top: anchor(bottom, 20px); }
.d { top: anchor(--other bottom, 20px); }
.e { top: calc(anchor(bottom) + 8px); }The last line shows that anchor() works inside calc(). That is often a cleaner way to add a gap than a margin, because the gap does not depend on which side the element sits on.
How an inset value is interpreted
An inset property does not measure from the same place as the anchor side keyword. Each inset property measures from one edge of the element's containing block to the matching edge of the element:
topis the distance from the containing block's top edge to the element's top margin edge.bottomis the distance from the containing block's bottom edge to the element's bottom margin edge.leftandrightwork the same way horizontally.
When you write bottom: anchor(top), the browser finds the anchor's top edge and works out how far that edge is from the bottom of the containing block. It then uses that distance as the bottom inset. You do not have to do this arithmetic. You choose which edge of the tooltip meets which edge of the anchor.
| Goal | Declarations |
|---|---|
| Above the anchor | `bottom: anchor(top)` |
| Below the anchor | `top: anchor(bottom)` |
| To the right of the anchor | `left: anchor(right)` |
| To the left of the anchor | `right: anchor(left)` |
| Top edges aligned | `top: anchor(top)` |
| Left edges aligned | `left: anchor(left)` |
In the top four rows the element touches the outside of the anchor. In the last two rows the element shares an edge with the anchor, so it overlaps it.
Matching the property to the side
Not every side keyword is valid in every property. The axis must match.
- In
topandbottom(andinset-block-startandinset-block-end), usetop,bottom,center, or a percentage. - In
leftandright(andinset-inline-startandinset-inline-end), useleft,right,center, or a percentage.
A mismatch such as top: anchor(left) is not valid. The browser treats the property as invalid at computed-value time and uses the fallback value if you gave one. If you did not, the property behaves as auto.
center is accepted in both axes. In a horizontal inset it is the horizontal center of the anchor. In a vertical inset it is the vertical center.
Logical keywords
You can also use keywords tied to the writing mode instead of the physical screen:
startandendresolve along the axis of the inset property, using the writing mode of the element's containing block.self-startandself-enddo the same, using the writing mode of the anchored element itself.
These help if your layout must work in right-to-left or vertical writing modes. For a simple tooltip in a left-to-right page, the physical keywords are easier to read.
Percentages
A percentage picks a point along the anchor's side. 0% is the start edge and 100% is the end edge. 50% is the center, so anchor(50%) in a horizontal inset is the same as anchor(center). A value of 25% is a quarter of the way along.
.badge {
position: absolute;
position-anchor: --avatar;
left: anchor(100%);
top: anchor(0%);
translate: -50% -50%;
}This pins a small badge to the top-right corner of an avatar. The translate centers the badge on that corner point. The badge is inside its own box model, so it does not take up space in the avatar's layout.
Stretching between two edges
You can set both insets on one axis. The element then takes its size from the distance between the two anchor edges, as long as its width or height on that axis is auto.
.underline {
position: absolute;
position-anchor: --heading;
top: anchor(bottom);
left: anchor(left);
right: anchor(right);
}Here .underline is as wide as the anchor and sits directly below it. The element is not sized by the anchor in any special way. This is the normal rule for absolutely positioned boxes: with left, right and width: auto, the box fills the space between the two insets. The next chapters cover anchor-size() for cases where you want to size from the anchor without pinning both edges.
Fallback values and failures
anchor() cannot resolve in several situations:
- The element is not absolutely or fixed positioned.
- The named anchor does not exist.
- The element has no
position-anchorand the call does not name an anchor. - The anchor is not a valid anchor for this element. For example, it comes after the element in a way the tree-order rules do not allow, or it is hidden inside another element's scope.
When it cannot resolve, the second argument is used.
.tooltip {
position: absolute;
position-anchor: --tip;
bottom: anchor(top, 100%);
left: anchor(center, 0px);
}If --tip is missing, the tooltip uses bottom: 100% and left: 0px instead. These values are measured against the containing block, so the tooltip lands somewhere predictable instead of falling back to auto.
The flowchart shows how the browser resolves one anchor() call.
Common errors
- The element is not positioned.
anchor()only works on elements withposition: absoluteorposition: fixed. On astaticorrelativeelement it does nothing. - No link to an anchor. Declaring
anchor-nameon the trigger is not enough. The tooltip needsposition-anchor: --tip, or each call must name the anchor, as inanchor(--tip top). - A mismatched axis.
left: anchor(top)is invalid. Keep horizontal keywords in horizontal insets and vertical keywords in vertical insets. - A wrong mental model of
bottom.bottom: anchor(top)does not mean "put the bottom at the top of the anchor's box measured from the top of the page." It means the element's bottom edge lands on the anchor's top edge. If the tooltip appears below the anchor, you likely wrotetop: anchor(top)instead. - Forgetting the centering shift.
left: anchor(center)aligns the element's left edge, not its center, to the anchor's center. Addtranslate: -50% 0, or useposition-area, covered in the next chapter. - Duplicate names. If several elements use
anchor-name: --tip,anchor()resolves to one of them, normally the last one before the positioned element in tree order. Anchor scoping, covered later, fixes this.
Where anchor() fits among the tools
anchor() gives you exact control. You choose each edge and can combine it with calc(), percentages and fallback lengths. It also takes more declarations than the other approach: a normal placement needs two insets, often a translate, and a margin.
The position-area property, which the next chapter introduces, replaces most of those declarations with a single keyword when you want a standard placement such as "above and centered." Use anchor() when you need an offset that a grid cell cannot express, such as a badge on a corner or an element stretched between two edges.
Exercise
A .menu element is absolutely positioned and has position-anchor: --btn. Write the two inset declarations that place it directly below the anchor with its left edge aligned to the anchor's left edge, with an 8px gap using calc(). Then say why top: anchor(left) would fail.
Show answer
top: calc(anchor(bottom) + 8px); left: anchor(left);. The top property is a vertical inset, so it accepts only vertical keywords (top, bottom, center) or a percentage. left is a horizontal keyword. The mismatch makes the declaration invalid at computed-value time, and it behaves as auto unless a fallback value is given.
Exercise
Why does left: anchor(center) on its own put a tooltip off-center, and which two declarations from this chapter fix it?
Show answer
left sets the tooltip's left edge, so the left edge, not the middle, sits at the anchor's center. Adding translate: -50% 0 moves the tooltip back by half its own width, which centers it. Replacing the left and translate pair with the percentage form does not help here, because the problem is the element's own width, so the shift is needed.