What is anchor positioning?
Learn CSS anchor positioning basics.
What is anchor positioning?
CSS anchor positioning is a declarative way to place one element relative to another. The first element becomes the anchor; the second binds to it and follows it. It is designed for dropdown menus, tooltips, and info popovers.
Placing a menu under a button used to need JavaScript offset math. Anchor positioning moves that math into CSS; on scroll and resize the menu stays put automatically.
Anchor and positioned element
Anchor positioning brings two roles together. The anchor is the reference point; typically a button, link, or info icon. The positioned element is the tooltip, dropdown, or popover bound to the anchor.
The anchor sits in the normal flow. The positioned element must be position: absolute or position: fixed; anchor positioning works only on positioned elements.
Why it matters
Anchor positioning has three advantages. First, you drop the JavaScript offset math; the position is fully defined in CSS. Second, when the anchor scrolls or the window resizes, the positioned element stays in place automatically.
Third, collision resolution is built in; if the element would overflow the viewport, the browser tries another position. All of this arrives step by step in the next lessons.
Exercise Set up the popover base
Write a .popover selector. The block must contain position: absolute and background: white. This is the positioned-element base that anchor positioning requires.
Show example solution
/* popover base */
.popover {
position: absolute;
background: white;
}
Test yourself
-
What does anchor positioning let you do?
- Smooth out color transitions
- Shrink CSS file size
- Bind one element to an anchor and have it follow
- Prevent page scrolling
Show answer
Bind one element to an anchor and have it follow — Correct. The bound element follows the anchor automatically as the anchor moves.
-
The positioned element's position value
.popover { position: ____; background: white; }Show answer
.popover { position: absolute; background: white; }