Using CSS offset-path with SVG Paths

The CSS offset-path property allows developers to position and animate any standard DOM element along a predefined vector trajectory originally defined by an SVG path. By linking coordinate geometry to an element’s layout properties, offset-path bridges the gap between vector graphics and DOM animation, enabling complex motion paths without relying on heavy JavaScript calculation libraries.

Linking via the path() Function

The most direct way to link a DOM element to SVG path coordinates is using the CSS path() function. This function accepts a standard SVG path data string—identical to what is used in the d attribute of an SVG <path> element.

.moving-element {
  offset-path: path("M 20 20 H 200 V 200 H 20 Z");
}

When this property is applied, the browser parses the SVG path commands (such as M for moveto, C for cubic Bézier curves, and L for lineto) and maps the element’s anchor point directly onto the coordinates defined within the string.

Linking via the url() Function

Alternatively, offset-path can directly reference an existing SVG element within the DOM using the url() function:

.moving-element {
  offset-path: url(#motionTrajectory);
}
<svg width="0" height="0">
  <path id="motionTrajectory" d="M 10 80 Q 95 10 180 80 T 350 80" />
</svg>

Using url() allows you to reuse visual SVG paths rendered on the page as physical tracks for HTML elements.

How Positioning and Motion Are Calculated

Once linked, the DOM element’s position is calculated based on three primary CSS Motion Path properties:

  1. offset-path: Sets the coordinate path geometry.
  2. offset-distance: Determines where the element sits along that path, measured from 0% (start) to 100% (end), or via fixed length units (e.g., px).
  3. offset-rotate: Automatically aligns the element’s orientation to the tangent angle of the path at its current position (default is auto).
  4. offset-anchor: Defines the transformation origin of the DOM element that sits directly on the path line (default is auto, aligning with transform-origin).

Animation Example

To animate a DOM element along the linked SVG path, pair offset-path with a CSS keyframe animation modifying the offset-distance:

.target-box {
  width: 40px;
  height: 40px;
  background-color: #007acc;
  
  /* Link to SVG geometry */
  offset-path: path("M 50 100 C 150 0, 250 200, 350 100");
  offset-rotate: auto;
  
  /* Animate along the path */
  animation: followPath 4s infinite linear;
}

@keyframes followPath {
  0% {
    offset-distance: 0%;
  }
  100% {
    offset-distance: 100%;
  }
}

By connecting geometric path definitions directly to standard CSS layout engines, offset-path offers high-performance, GPU-accelerated motion tracking for modern web interfaces.