This content originally appeared on Manuel Matuzović - Web development blog and was authored by Manuel Matuzović
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.
<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;
}
My blog doesn't support comments yet, but you can reply via blog@matuzo.at.
This content originally appeared on Manuel Matuzović - Web development blog and was authored by Manuel Matuzović
Manuel Matuzović | Sciencx (2023-01-25T09:38:54+00:00) Day 88: CSS Motion Path. Retrieved from https://www.scien.cx/2023/01/25/day-88-css-motion-path/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.