Sub topic 1
CSS Anchor Positioning: Attaching Elements to Other Elements in Pure CSS
Prerequisites
You should know basic CSS selectors, the cascade, the box model, and position: relative and position: absolute. You should also understand inset properties such as top, left, and bottom.
Before anchors: absolute positioning and containing blocks
An absolutely positioned element is removed from normal document flow. Its offsets are calculated against its containing block, usually the nearest ancestor whose position is not static.
.card {
position: relative;
}
.tooltip {
position: absolute;
top: 0;
left: 100%;
margin-left: 8px;
}Here, .card establishes the containing block. Without it, the tooltip might be positioned relative to a more distant ancestor or the initial containing block. This approach works when the target has a predictable container, but it does not directly express “place this beside that button.”
Declaring an anchor and linking an element to it
An anchor is an element that another positioned element can reference. Give it a name with anchor-name, then connect the positioned element with position-anchor.
<button class="trigger">Help</button>
<div class="tooltip">More information</div>.trigger {
anchor-name: --tip;
}
.tooltip {
position: absolute;
position-anchor: --tip;
}The custom identifier --tip associates the tooltip with the button. The tooltip still needs placement rules.
Placing an element with `anchor()`
The anchor() function reads an edge or position from the associated anchor. This tooltip touches the button’s top edge and centers itself horizontally.
.trigger {
anchor-name: --tip;
}
.tooltip {
position: absolute;
position-anchor: --tip;
bottom: anchor(top);
left: anchor(center);
translate: -50% 0;
margin-bottom: 8px;
}bottom: anchor(top) places the tooltip’s bottom edge at the button’s top edge. left: anchor(center) aligns the tooltip’s left edge with the button’s center. translate: -50% 0 moves the tooltip left by half its own width.
Placing an element with `position-area`
position-area uses a 3-by-3 grid around the anchor. The top area places the element above the anchor and centers it horizontally.
.tooltip {
position: absolute;
position-anchor: --tip;
position-area: top;
margin-bottom: 8px;
}This expresses the intended relationship more directly than manual offsets. Later, fallback rules can move the tooltip when the top area has insufficient space.
Exercise
What does bottom: anchor(top) align?
Show answer
It aligns the anchored element’s bottom edge with the anchor’s top edge.