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: calc(attr(max type(<integer>)) - 1);
padding-inline: calc(var(--s)/2);
mask: 0 calc(.4*var(--s))/var(--s);
mask-image:
conic-gradient(from 162deg at 50% 65%,#000 .1turn,#0000 0),
conic-gradient(from 18deg at 21% 55%,#000 .1turn,#0000 0),
conic-gradient(from 306deg at 79% 55%,#000 .1turn,#0000 0);
appearance: none;
cursor: pointer;
}
input[type="range" i]::-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: calc(attr(max type(<integer>)) - .5);
padding-inline: calc(var(--s)/4);
mask: 0 calc(.4*var(--s))/var(--s);
mask-image:
conic-gradient(from 162deg at 50% 65%,#000 .1turn,#0000 0),
conic-gradient(from 18deg at 21% 55%,#000 .1turn,#0000 0),
conic-gradient(from 306deg at 79% 55%,#000 .1turn,#0000 0);
appearance: none;
cursor: pointer;
}
input[type="range" i]::-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.