Dynamic Tooltip Position with Anchor Positioning II
In the previous post, we created a tooltip that flips between two positions to remain visible. It's either on the top or the bottom. We can adjust the code to do the same with four positions (top, bottom, left, and right). And whatever the position of the tooltip, the tail will always point to the anchor.
#anchor {
position: absolute;
anchor-name: --anchor;
}
#tooltip {
--d: 1em; /* distance between anchor and tooltip */
--s: .8em; /* tail size */
position: absolute;
position-anchor: --anchor;
/* we place the tooltip at the top */
position-area: top;
bottom: var(--d);
margin: var(--d);
margin-bottom: 0;
/* If top is not available with flip to bottom,
else if bottom is not available, we move to left,
else if left is not available, we move to right */
position-try-fallbacks: flip-block,--flip-left,--flip-right;
}
@position-try --flip-left {
position-area: left;
right: var(--d);
margin: var(--d);
margin-right: 0;
}
@position-try --flip-right {
position-area: right;
left: var(--d);
margin: var(--d);
margin-left: 0;
}
/* the tail */
#tooltip:before {
content:"";
position: absolute;
z-index: -1;
background: inherit;
inset: calc(-1*var(--d));
margin: inherit; /* the margin will do the magic and only show one part of the shape */
/* the shape of the 4 arrows with one clip-path */
clip-path: polygon(
calc(50% - var(--s)) var(--d),50% .2em,calc(50% + var(--s)) var(--d),
calc(100% - var(--d)) calc(50% - var(--s)), calc(100% - .2em) 50%,calc(100% - var(--d)) calc(50% + var(--s)),
calc(50% + var(--s)) calc(100% - var(--d)),50% calc(100% - .2em),calc(50% - var(--s)) calc(100% - var(--d)),
var(--d) calc(50% + var(--s)), .2em 50%,var(--d) calc(50% - var(--s))
);
}
Here is an interactive demo where you can drag the anchor and see how the tooltip behaves:
See the Pen Follow me if you can! (drag the anchor) by Temani Afif (@t_afif) on CodePen.
If you click on "debug mode" you can see the global shape created with the pseudo-element that contains the four arrows.
More CSS Tips
- Dynamic Tooltip Position with Anchor Positioning A tootlip that follows its anchor while adjusting the position of its tail.
- Range Selection using Modern CSS A new way to select elements in a specific range using if() and sibling-index().