Exploring Code #69: Anchor Positioning API in CSS
This one isn't quite ready for production-use yet, but it's getting there at 67% global availability.
Regardless, it will be a really useful tool in your arsenal once you can safely use it.
I'm talking about the anchor positioning API.
Syntax for the Anchor Positioning API
Instead of applying position absolute to elements inside of a relatively positioned container and worrying about the introduction or rearrangement of the elements in the future - think popovers, tooltips, etc. - you can get more precise and future-proof by explicitly controlling which elements are 'tethered' despite arrangement of nodes.
The syntax looks kind of like CSS variables with the double dashes --.
You also need to make sure you are using either positioned fixed or positioned absolute on the element that will move around.
Here's the first step:
Where you have some HTML:
领英推荐
<div class="wrap">
<a class="anchor-element">
<!--Not real anchor SVG markup for brevity-->
<svg xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink" xmlns:a="https://ns.adobe.com/AdobeSVGViewerExtensions/3.0/" version="1.1</path></svg>
</a>
<div class="tippy">
<h3>Anchor Positioning API Example</h3>
<p>Good shit</p>
</div>
</div>
And some CSS to kick things off:
Notice the anchor-name: --anchor and position-anchor: --anchor declarations.
.anchor-element {
anchor-name: --anchor;
cursor: pointer;
display: flex;
flex-flow: column;
gap: 1rem;
}
.tippy {
opacity: 0;
position: absolute;
position-anchor: --anchor;
}
And the second step does all the magic - this is where you apply the positioning to the anchor element.
We add - top: anchor(bottom) to position the tooltip to the anchor element.
We add - justify-self: anchor-center; to center the tooltip.
.anchor-element {
anchor-name: --anchor;
cursor: pointer;
display: flex;
flex-flow: column;
gap: 1rem;
}
.tippy {
opacity: 0;
position: absolute;
position-anchor: --anchor;
top: anchor(bottom);
justify-self: anchor-center;
}
/* this is added only for hover and layout purposes */
body:has(.anchor-element:hover) .tippy {
opacity: 1;
visibility: visible;
transition: ease-in .2s all;
}
.wrap {
height: 100vh;
display: grid;
place-content: center;
}
/* this is added only for hover and layout purposes */