One of my greatest joys is hacking around with Tailwind CSS, and using it to build things that feel like they should need Javascript, with just plain HTML and CSS.
This Tailwind star rating input is a perfect example. With just plain HTML and Tailwind classes, you can build an animated star rating component just like below.
Here’s the star rating input:
And here’s the code:
<div class="text-5xl flex flex-row-reverse justify-center gap-1 text-amber-950">
<a id="rate-5" href="#5" class="transition-all peer hover:text-yellow-500 peer-hover:text-yellow-500 cursor-pointer">★</a>
<a id="rate-4" href="#4" class="transition-all peer hover:text-yellow-500 peer-hover:text-yellow-500 cursor-pointer">★</a>
<a id="rate-3" href="#3" class="transition-all peer hover:text-yellow-500 peer-hover:text-yellow-500 cursor-pointer">★</a>
<a id="rate-2" href="#2" class="transition-all peer hover:text-yellow-500 peer-hover:text-yellow-500 cursor-pointer">★</a>
<a id="rate-1" href="#1" class="transition-all peer hover:text-yellow-500 peer-hover:text-yellow-500 cursor-pointer">★</a>
</div>
For a quick breakdown of the component:
href
attribute on each a
tag. For instance, if someone clicks stars 4 or 5, you could redirect them to a public review website to leave a nice review, but if they click stars 1, 2 or 3, you could redirect them to a feedback form.flex-flow-reverse
. This accounts for how peer-hover
interacts with its siblings. Without inverting, the stars fade in from the right, which is odd. We invert everything so that hovering over a star colors all the stars to its left instead.Thanks for reading!
I hope you found this Tailwind star rating input handy. I’ve written previously about building with native HTML and Tailwind, you might find it interesting.