A single-element star rating component (without JS)
Transform the native range slider into a star rating component using a few lines of CSS and zero JavaScript. You can adjust the number of stars by simply changing the max
attribute.
Yes, you can click to update the rating. It's an interactive widget!
<input type="range" min="1" max="5">
input[type="range"] {
--s: 100px; /* control the size */
height: var(--s);
aspect-ratio: attr(max type(<integer>));
padding-inline: calc(var(--s)/2);
box-sizing: border-box;
mask: url("data:image/svg+xml;utf8,<svg><path d='path_of_a_star_shape'/></svg>") 0/var(--s);
appearance: none;
}
input[type="range"]::-webkit-slider-thumb{
width: 1px;
border-image:
conic-gradient(at calc(50% + var(--s)/2),#7b7b7b 50%,#fff220 0)
fill 0//var(--s) calc(20*var(--s));
appearance: none;
}
See the Pen CSS-Only Rating Component (Click to update!) by Temani Afif (@t_afif) on CodePen.
We can update the code slightly to get a variation that works with half stars.
<input type="range" min=".5" step=".5" max="5">
input[type="range"] {
--s: 100px; /* control the size*/
height: var(--s);
aspect-ratio: attr(max type(<integer>));
padding-inline: calc(var(--s)/4);
box-sizing: border-box;
mask: url("data:image/svg+xml;utf8,<svg><path d='path_of_a_star_shape'/></svg>") 0/var(--s);
appearance: none;
}
input[type="range"]::-webkit-slider-thumb{
width: 1px;
border-image:
conic-gradient(at calc(50% + var(--s)/4),#7b7b7b 50%,#fff220 0)
fill 0//var(--s) calc(10*var(--s));
appearance: none;
}
See the Pen CSS-Only Rating Component (Click to update!) by Temani Afif (@t_afif) on CodePen.
More detail: A CSS-Only Star Rating Component and More!