Description
The example in the draft showing how to use the anchor
function with math functions involves verbose and complex calculations to center an element over its anchor: https://drafts.csswg.org/css-anchor-position-1/#example-a7ac0832
.centered-message {
position: fixed;
max-width: max-content;
justify-self: center;
--center: anchor(--x 50%);
--half-distance: min(
abs(0% - var(--center)),
abs(100% - var(--center))
);
left: calc(var(--center) - var(--half-distance));
right: calc(var(--center) - var(--half-distance));
bottom: anchor(--x top);
}
This was noted months ago at #8979 and the anchor-center
value was added as an easy way to achieve a similar behavior. However, the example remains the same at the specs and there isn't another example of using math functions with anchor()
in a useful way.
So I think it would be better to:
- remove the current example from the spec and,
- add a new example showing off
anchor()
with math functions
Some examples could be using calc()
to position an element a little inside its anchor top corner, like a notification:
https://codepen.io/monknow/pen/gONevrr
.target {
--target-height: 30px;
--target-width: 20px;
position: absolute;
position-anchor: --my-anchor;
left: calc(anchor(right) - var(--target-width) / 2);
bottom: calc(anchor(top) - var(--target-height) / 2);
height: var(--target-height);
width: var(--target-width)
}
Or this one by Jhey Tompkins that uses max()
to attach a tooltip to the tallest element and min()
to the smallest.
https://codepen.io/web-dot-dev/pen/PoeNKXJ
.chart__tooltip--max {
position: absolute;
left: anchor(--chart right);
bottom: max(
anchor(--anchor-1 top),
anchor(--anchor-2 top),
anchor(--anchor-3 top)
);
}
.chart__tooltip--min {
position: absolute;
right: calc(anchor(--chart left) + 1rem);
bottom: min(
anchor(--anchor-1 top),
anchor(--anchor-2 top),
anchor(--anchor-3 top)
);
}