CSS Anchor Positioning Overview
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
Positioning an Element Relative to Another, the Old Way
Placing a tooltip or dropdown menu precisely next to a specific button - and having it intelligently flip position if it would otherwise overflow the screen - has traditionally required a JavaScript positioning library that measures both elements and calculates coordinates manually.
Step 1: Declare an Anchor
.trigger-button {
anchor-name: --my-button;
}Any element can be marked as an anchor by giving it a custom anchor name, similar in spirit to a custom property name.
Step 2: Position Another Element Relative to It
.tooltip {
position: absolute;
position-anchor: --my-button;
top: anchor(bottom);
left: anchor(center);
}The anchor() function reads a specific edge or point of the anchor element - here, positioning the tooltip just below the button's bottom edge, horizontally centered on it - without any JavaScript measuring involved.
Automatic Fallback Positioning
.tooltip {
position-try-fallbacks: flip-block;
}position-try-fallbacks lets a positioned element automatically try an alternative placement - such as flipping to appear above the anchor instead of below - if the preferred position would overflow the viewport, a common requirement for tooltips and dropdown menus near the edge of the screen.
Why This Is a Meaningful Change
Anchor positioning moves a whole category of positioning logic - previously requiring a JavaScript library - directly into native CSS, reducing the amount of script needed to build things like tooltips, popovers and dropdown menus that must stay attached to a trigger element.