Anchor() function
Learn positioning with the anchor() function.
The anchor() function
The anchor() function returns a position value relative to the anchor's edges. Writing top: anchor(bottom); aligns the element's top edge with the anchor's bottom edge. This is the natural way to place a tooltip below a button.
The keyword inside the parentheses names an anchor edge: top, bottom, left, right, start, end, center. You write whichever edge the element should align to.
anchor() keywords
The most common anchor() keywords are: top, bottom, left, right for the anchor edges, and center for the anchor's middle. start and end map to left or right based on writing direction.
Two axes combine. For example, top: anchor(bottom); left: anchor(center); places the element below the anchor, centered horizontally. This is the classic dropdown placement.
Exercise Place the tooltip below the anchor
Write a .tooltip selector. The block must contain position-anchor: --info-button and top: anchor(bottom). This places the tooltip below the button.
Show example solution
/* place the tooltip below the anchor */
.tooltip {
position-anchor: --info-button;
top: anchor(bottom);
}
Test yourself
-
What does <code>top: anchor(bottom)</code> do?
.tooltip { position: absolute; position-anchor: --info; top: anchor(bottom); }- It pins the tooltip to the anchor's top edge
- It pins the tooltip to the anchor's center
- It places the tooltip at the same spot as the anchor
- It aligns the tooltip's top edge with the anchor's bottom edge
Show answer
It aligns the tooltip's top edge with the anchor's bottom edge — Correct. top: anchor(bottom) aligns the element's top edge with the anchor's bottom edge; the tooltip goes below.
-
Place the tooltip below the anchor
.tooltip { position-anchor: --info; top: anchor(____); }Show answer
.tooltip { position-anchor: --info; top: anchor(bottom); } -
Match each anchor() keyword to its position
- anchor(bottom)
- Anchor's bottom edge
- anchor(top)
- Anchor's top edge
- anchor(center)
- Anchor's center
- anchor(right)
- Anchor's right edge