CSS path() Function
The path() function allows you to define a custom shape using an SVG path data string.
While CSS provides basic shape functions like circle(), ellipse(), and polygon(), they can be limiting when you need to create complex shapes with curves. The path() function bridges this gap by bringing the full drawing power of SVG directly into your CSS.
You can use the path() function with several CSS properties, most notably clip-path (to cut out a shape from an element), offset-path (to animate an element along a specific route), and shape-outside (to wrap text around a custom shape).
Here is an example of using the path() function with the clip-path property to crop a square div into a custom curved shape:
Animating Along a Path
One of the most exciting uses for the path() function is combining it with the offset-path property. This allows you to define a custom trajectory for an element to follow during an animation.
By animating the offset-distance property from 0% to 100%, the element will travel along the exact coordinates defined in your SVG path string. The browser will even automatically rotate the element so that it faces the direction of the path as it moves.
Here is an example of an element animating along a wavy path:
Fill Rules
When drawing complex paths that intersect themselves, the browser needs to know how to determine what is "inside" the shape and what is "outside". The path() function accepts an optional fill rule parameter to control this.
nonzero: This is the default rule. It determines the "insideness" of a point by drawing a ray from that point to infinity and counting the path segments it crosses, factoring in the direction the path was drawn.evenodd: This rule determines the "insideness" of a point by drawing a ray from that point to infinity and simply counting the number of path segments it crosses. If the number is odd, the point is inside; if even, it is outside.
Official Syntax
The official syntax of the path() function is as follows:
Where <fill-rule> is defined as:
Possible Values
As indicated in the official syntax, the path() function accepts the following values:
- fill-rule
An optional keyword (
nonzeroorevenodd) that specifies how to determine the inside of the shape. If omitted, it defaults tononzero.- string
A string containing valid SVG path data (e.g.,
"M 10 10 L 90 10 L 90 90 Z"). The string must be enclosed in quotes.
CSS Specifications
- The
path()function is defined in CSS Shapes Module Level 1 (W3C Candidate Recommendation)
Browser Support
The following table provided by Caniuse.com shows the level of browser support for this feature.