I often feel intimidated initially by new CSS things.. I've been putting off the new CSS Anchor api stuff cuz it looked scary.
But not 15m minutes into actually sitting with it, and I'm stoked.
basics #
You need something to anchor to, just like you need a named container or a view-timeline.
.some-non-floating-element {
anchor-name: --side;
}
Next, assign some element's positions to that anchor. Let's say we want to put a floating element underneath that non-floating one. We'd want the top of the floating thing to be touching the bottom of the anchor:
.tooltippy {
position: absolute;
top: anchor(--side bottom);
/* top of this touches the bottom of that */
}
Then, we want the left side of this tooltip to align with the left side of the anchor:
.tooltippy {
left: anchor(--side left);
/* left of this touches the left of that */
}
Now it's aligned with it: left aligned and under!
Resources #
Dig in:
- Jhey has a fantanstic anchor() collection on Codepen
- He also covers anchoring in a piece on the Chrome Developers Blog called Popups They're Making A Resurgence
- Official Explainer
- Official Spec