DEV Community

WDSEGA
WDSEGA

Posted on • Originally published at wdsega.github.io

Component Deep Dive #19: Star Rating - The CSS Color Magic Behind 5 Stars

Web Component Dictionary v2.0 - 83 Components / 8 Categories / Bilingual / Live Preview
Live Demo | Buy

The star rating component is a staple of every product page. Here is how to build a fully functional, accessible version with minimal code.

The Core CSS Trick

.ef-star.hovered, .ef-star.selected { color: #f59e0b; }
.ef-star:hover { transform: scale(1.2); }
Enter fullscreen mode Exit fullscreen mode

The JS Logic

stars.forEach((star, i) => {
  star.addEventListener('mouseenter', () => updateDisplay(i+1, currentRating));
  star.addEventListener('mouseleave', () => updateDisplay(0, currentRating));
  star.addEventListener('click', () => {
    currentRating = i+1;
    updateDisplay(0, currentRating);
  });
});
Enter fullscreen mode Exit fullscreen mode

Accessibility

  • Add role="radiogroup" on the container
  • Add role="radio" and aria-label on each star
  • Support Enter and Space keys for keyboard navigation

Key Pitfalls

  • Always add user-select: none to prevent text selection on drag
  • Do not use native input[type=radio] - native CSS styling is extremely difficult
  • Store current value in data-rating attribute for easy form submission

Full code and bilingual article

Top comments (0)