Day 88: CSS Motion Path

posted on

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.


CSS Motion path allows you to position any graphical object and animate it along a specified path.

Let's you have a path, and you want to animate an element along that path.

Note: You don't need the <svg> to achieve that, but for the sake of understanding, I'm using it in this demo to visualize the path. I've placed the square on top of the svg using absolute positioning.
<svg width="305" height="144">
  <path stroke="#000" fill="none" stroke-width="4" d="m4,139c0,-1.31731 7.78207,-137 121.62162,-137c113.83955,0 85.71428,133.04808 178.37837,127.12019">
</svg>
<div class="square"></div>
.square {
  background: hsl(93deg 75% 49%);
  height: 2em;
  width: 2em;
  position: absolute;
  inset-inline-start: 0;
  inset-block-start: 0;
}

Because of the absolute positioning, the .square is at the top left corner of its parent element. If you want to put the .square on a path (Note: not the actual path of the svg, but its own path), you can use the offset-path property. Just copy the value of the <path>s d attribute and put it in a path() function.

.square {
  offset-path: path("m4,139c0,-1.31731 7.78207,-137 121.62162,-137c113.83955,0 85.71428,133.04808 178.37837,127.12019");
}

The .square is now positioned on the path and can be moved, using offset-distance.

.square {
  offset-path: path("m4,139c0,-1.31731 7.78207,-137 121.62162,-137c113.83955,0 85.71428,133.04808 178.37837,127.12019");
  offset-distance: 30%;
}

You can also rotate it, using offset-rotate.

.square {
  offset-path: path("m4,139c0,-1.31731 7.78207,-137 121.62162,-137c113.83955,0 85.71428,133.04808 178.37837,127.12019");
  offset-distance: 30%;
  offset-rotate: 13deg;
}

Of course, you can also animate these properties.

.square {
  offset-path: path("m4,139c0,-1.31731 7.78207,-137 121.62162,-137c113.83955,0 85.71428,133.04808 178.37837,127.12019");
  animation: move 2s infinite;
}

@keyframes move {
  0% {
    offset-distance: 0%;
  }

  100% {
    offset-distance: 100%;
  }
}

For the sake of completeness, the same demo without the svg.

<div class="parent">
  <div class="square"></div>
</div>
.parent {
  height: 150px;
}

.square {
  offset-path: path("m4,139c0,-1.31731 7.78207,-137 121.62162,-137c113.83955,0 85.71428,133.04808 178.37837,127.12019");
  animation: move 2s infinite;
  position: static;
}

See on CodePen

Further reading

Overview: 100 Days Of More Or Less Modern CSS