Sub topic 3
Hiding Anchored Elements with `position-visibility`
Assume you know CSS selectors, the cascade, containing blocks, and position: absolute with inset properties. Anchor positioning adds rules for keeping related elements usable as the page moves.
Hiding Anchored Elements
An anchored element can become useless when its anchor scrolls out of view. position-visibility lets the browser hide it automatically.
.tooltip {
position: absolute;
position-anchor: --tip;
position-area: top;
position-visibility: anchors-visible;
}anchors-visible hides the tooltip when its anchor is clipped by an overflow ancestor. Other useful values include no-overflow, which hides the element when it would overflow its containing block, and always, the default behavior.
Scrolling and Overflow
The browser recalculates an anchored element's position as its anchor moves during scrolling. You do not need a scroll event listener or JavaScript measurements.
Overflow still matters. A clipping ancestor can hide the anchor or the anchored element. Test inside scrollable panels, not only against the viewport.
Reusing Names with `anchor-scope`
Anchor names can be reused in separate components. anchor-scope limits where a name can be found, preventing one component from accidentally selecting another component's anchor.
.card {
anchor-scope: --tip;
}
.card .trigger {
anchor-name: --tip;
}
.card .tooltip {
position: absolute;
position-anchor: --tip;
position-area: top;
}Each card can now use --tip independently.
Anchoring Popovers and Menus
The Popover API supplies keyboard behavior and places the popover in the top layer. Connect it to its invoking button like this:
<button id="menu-btn" popovertarget="menu">Menu</button>
<div id="menu" popover>
<a href="/profile">Profile</a>
<a href="/settings">Settings</a>
</div>#menu-btn {
anchor-name: --menu-btn;
}
#menu {
position-anchor: --menu-btn;
position-area: bottom span-right;
inset: auto;
margin: 0;
position-try-fallbacks: flip-block;
}The fallback moves the menu above the button when there is not enough room below it.
Feature Detection and Fallbacks
Use a normal layout first, then enhance it when anchor positioning is supported.
.tooltip {
position: static;
}
@supports (anchor-name: --a) {
.tooltip {
position: absolute;
position-anchor: --tip;
position-area: top;
}
}Exercise
Which property hides a tooltip when its anchor is clipped, and which property limits an anchor name to a component?
Show answer
Use position-visibility: anchors-visible and anchor-scope: --name.