I want to create a unique SVG star rating component using a single SVG.
The shape consists of 5 stars filled with a horizontal gradient. Take a look at the following code snippet:
<svg width="68" height="11" viewBox="0 0 68 11">
<linearGradient id="grad">
<stop offset="70%" stop-color="tomato"/>
<stop offset="70%" stop-color="grey"/>
</linearGradient>
<g fill="url(#grad)">
<path d="M6 8.84L9.708 11l-.984-4.07L12 4.192l-4.314-.354L6 0 4.314 3.838 0 4.192 3.276 6.93 2.292 11zM20 8.84L23.708 11l-.984-4.07L26 4.192l-4.314-.354L20 0l-1.686 3.838L14 4.192l3.276 2.738-.984 4.07zM34 8.84L37.708 11l-.984-4.07L40 4.192l-4.314-.354L34 0l-1.686 3.838L28 4.192l3.276 2.738-.984 4.07zM48 8.84L51.708 11l-.984-4.07L54 4.192l-4.314-.354L48 0l-1.686 3.838L42 4.192l3.276 2.738-.984 4.07zM62 8.84L65.708 11l-.984-4.07L68 4.192l-4.314-.354L62 0l-1.686 3.838L56 4.192l3.276 2.738-.984 4.07z"/>
</g>
</svg>
The star rating can be in decimals, not just full or half stars, such as 3.35
.
My main challenge is how to define offset="70%"
dynamically.
- Is there a way to pass a percentage to SVG? (e.g., using
currentColor
to pass color from CSS) - Is it possible to apply a linear gradient without referencing it by
url(#id)
? I want to avoid generating unique IDs for each rating on the page. - Or maybe there's a way to fill a certain percentage of horizontal space just through CSS?