CSS Anchor Positioning Polyfill

Anchoring Elements in the shadow DOM

Note: We strive to keep the polyfill up-to-date with ongoing changes to the spec, and we welcome code contributions and financial support to make that happen.

Works if anchor and target are both inside the same shadow root

With polyfill applied: Target and Anchor’s right edges line up. Target’s top edge lines up with the bottom edge of the Anchor.

Note: this will not work across shadow root boundaries, and will not work with constructed stylesheets.

<anchor-web-component>
  <template shadowrootmode="open">
    <style>
    #my-anchor-positioning {
      anchor-name: --my-anchor-positioning;
    }

    #my-target-positioning {
      position: absolute;
      top: anchor(--my-anchor-positioning bottom);
      right: anchor(--my-anchor-positioning right, 50px);
    }
    </style>
    <div style="position: relative">
      <div id="my-target-positioning">Target</div>
      <div id="my-anchor-positioning">Anchor</div>
    </div>
  </template>
</anchor-web-component>
<script>
class AnchorDemo extends HTMLElement {
  connectedCallback() {
    window.ANCHOR_POSITIONING_POLYFILL({ roots: [this.shadowRoot] });
  }
}
customElements.define("anchor-web-component", AnchorDemo);
</script>