Sub topic 2
Sizing Anchored Elements and Choosing Fallbacks
Assume you know CSS selectors, the cascade, absolute positioning, containing blocks, and inset properties such as top and left. This chapter uses an existing anchor named --menu-btn.
Sizing from the anchor with `anchor-size()`
The anchor-size() function reads a dimension from the anchor. Use it in a sizing property such as width, min-width, or block-size.
This dropdown is at least as wide as its button:
.dropdown {
position: absolute;
position-anchor: --menu-btn;
position-area: bottom span-right;
min-width: anchor-size(width);
}anchor-size(width) returns the anchor's border-box width. You can also use anchor-size(height) or logical dimensions such as anchor-size(inline). This avoids repeating a fixed width in CSS when the button's size can change.
Staying in view with `position-try-fallbacks`
An anchored element can overflow the viewport. A tooltip placed above a button may have no room near the top edge. position-try-fallbacks gives the browser alternative placements to test.
.tooltip {
position: absolute;
position-anchor: --tip;
position-area: top;
margin-bottom: 8px;
position-try-fallbacks: flip-block, flip-inline;
}The browser tries the main placement first. flip-block moves the tooltip to the opposite block direction, usually below the anchor. flip-inline tries the opposite inline direction. The browser uses the first placement that satisfies its overflow checks.
Writing custom fallbacks with `@position-try`
Use @position-try when a built-in flip does not describe the layout you need. The rule defines declarations for a named fallback:
@position-try --below {
position-area: bottom;
margin-top: 8px;
}
.tooltip {
position: absolute;
position-anchor: --tip;
position-area: top;
margin-bottom: 8px;
position-try-fallbacks: --below, flip-inline;
}The custom fallback can change position-area, margins, alignment, or other positioning declarations.
Picking the best fallback with `position-try-order`
Fallback order normally follows the list order. Use position-try-order when the browser should prefer a candidate based on available space rather than declaration order.
.tooltip {
position-try-order: most-block-size;
}most-block-size prefers the candidate with the most available block-axis space. This is useful when either side can work and you want the largest usable area.
Exercise
What happens when a tooltip's position-area: top placement overflows and position-try-fallbacks lists --below, flip-inline?
Show answer
The browser tries the custom --below placement first, then the horizontally flipped placement.