Tether elements to each other with CSS anchor positioning

Tether elements to each other with CSS anchor positioning

How do you currently tether one element to another? You might try tracking their positions, or use some form of wrapper element.

These solutions often aren't ideal. They need JavaScript or introduce extra markup. The CSS anchor positioning API aims to solve this by providing a CSS API for tethering elements. It provides a means to position and size one element based on the position and size of other elements.

You can try out the CSS anchor positioning API in Chrome Canary behind the "Experimental Web Platform Features" flag. To enable that flag, open Chrome Canary and visit chrome://flags. Then enable the "Experimental web platform features" flag.

There is also a polyfill in development by the team at Oddbird. Be sure to check the repo at github.com/oddbird/css-anchor-positioning.

[…]

But, what if you don't know the position of your anchor? You likely need to intervene with JavaScript. You could do something like the following code does, but now this means your styles are starting to leak out of CSS and into JavaScript.

[…]

Now you need to decide whether to react to this and how. The number of questions and decisions you need to make is starting to grow. All you want to do is anchor one element to another. And in an ideal world, your solution will adjust and react to its surroundings.

[…]

You could track the highest and lowest values using CSS min and max. The CSS for that could look something like this:

There is some JavaScript at play to update the chart values and some CSS to style the chart. But anchor positioning takes care of the layout updates for us.

[…]