CSS Project: Crafting a Simple, Pure CSS Animated Star Rating Component

Written by

in

In the world of web development, creating engaging user interfaces is paramount. One common element that enhances user experience is a star rating component. This project will guide you through building a simple, yet effective, animated star rating system entirely with CSS. This project is perfect for beginners and intermediate developers looking to deepen their CSS skills and learn how to create interactive elements without relying on JavaScript.

Why Build a CSS Star Rating Component?

Star ratings are a ubiquitous feature on the web. They provide users with a quick and intuitive way to express their opinions, review products, or rate services. Building one with CSS offers several advantages:

  • Performance: CSS-based animations are generally smoother and more performant than JavaScript-based animations, especially on mobile devices.
  • Accessibility: CSS allows for semantic HTML structure, making the component accessible to users with disabilities.
  • Maintainability: CSS is easy to understand and maintain, making it simple to update and customize the component.
  • Learning Opportunity: This project provides a hands-on opportunity to learn and practice essential CSS concepts like pseudo-classes, transitions, and animations.

Understanding the Core Concepts

Before diving into the code, let’s review the key CSS concepts we’ll be using:

  • Pseudo-classes: These are keywords added to selectors that allow you to style elements based on their state. For example, the `:hover` pseudo-class styles an element when the user hovers over it, and the `:checked` pseudo-class styles a checked checkbox or radio button.
  • Transitions: Transitions provide a smooth change between different states of an element. We will use transitions to animate the change in star color when a user hovers over or selects a star.
  • Animations: Animations allow you to create more complex effects, such as a pulsing or fading effect. Although we won’t use complex animations in this project, understanding them is valuable for future projects.
  • CSS Variables (Custom Properties): While not strictly required for this project, CSS variables can enhance maintainability by allowing you to store and reuse values like colors and sizes.

Step-by-Step Instructions: Building the Star Rating Component

Let’s build the star rating component. We’ll start with the HTML structure, then add CSS to style and animate it.

1. HTML Structure

First, we need the HTML. We’ll use a `

` element as a container and then create a series of “ elements of type “radio”. Each radio input will represent a star. We will also use `` elements to represent the stars themselves, using a star symbol from Unicode.

<div class="star-rating">
  <input type="radio" id="star5" name="rating" value="5" />
  <label for="star5"><span>★</span</label>
  <input type="radio" id="star4" name="rating" value="4" />
  <label for="star4"><span>★</span</label>
  <input type="radio" id="star3" name="rating" value="3" />
  <label for="star3"><span>★</span</label>
  <input type="radio" id="star2" name="rating" value="2" />
  <label for="star2"><span>★</span</label>
  <input type="radio" id="star1" name="rating" value="1" />
  <label for="star1"><span>★</span</label>
</div>

Here’s a breakdown:

  • We use radio inputs because only one star can be selected at a time, just like radio buttons.
  • Each input has a unique `id` and a `name` attribute. The `name` attribute groups the radio buttons.
  • Each input has a corresponding `label` element. The `for` attribute of the label matches the `id` of the input, associating the label with the input.
  • Inside each label, we place a `` element containing the star symbol (★).

2. Basic CSS Styling

Now, let’s add some CSS to style the stars and the container. We’ll set the star color, size, and layout.


.star-rating {
  display: inline-flex; /* or inline-block */
  direction: rtl; /* Right-to-left to make the hover effect work correctly */
  font-size: 2em; /* Adjust the size of the stars */
}

.star-rating input {
  display: none; /* Hide the radio inputs */
}

.star-rating label {
  color: #ccc; /* Default star color */
  cursor: pointer; /* Change cursor to a pointer on hover */
  transition: color 0.2s ease;
}

.star-rating label span {
  display: inline-block;
}

Explanation:

  • `.star-rating`: We set `display: inline-flex` (or `inline-block`) to arrange the stars horizontally. `direction: rtl` is crucial. It ensures that the hover effect works from right to left, filling the stars correctly.
  • `.star-rating input`: We hide the radio inputs because they are not needed for visual representation; labels will be used instead.
  • `.star-rating label`: We set the default star color to a light gray (`#ccc`) and add a `cursor: pointer` to indicate that the stars are interactive. We also add a transition for a smooth color change.
  • `.star-rating label span`: We make sure that the star symbols are rendered as inline-block elements.

3. Hover and Checked States

Now, let’s add the interactive behavior. We’ll use the `:hover` pseudo-class to change the star color when the user hovers over a star and the `:checked` pseudo-class to change the color of selected stars.


.star-rating label:hover, .star-rating label:hover ~ label {
  color: #ffc107; /* Star color on hover */
}

.star-rating input:checked ~ label {
  color: #ffc107; /* Star color for selected stars */
}

Explanation:

  • `.star-rating label:hover`: This changes the color of the hovered star to a gold color (`#ffc107`).
  • `.star-rating label:hover ~ label`: This is the key to filling the stars to the left of the hovered star. The `~` selector selects all preceding sibling elements. Thus, when you hover over a star, all the stars to the left of it will also change to gold.
  • `.star-rating input:checked ~ label`: This changes the color of all stars to the left of the checked input to gold.

4. Improving Accessibility

While the basic component works, we can improve accessibility. We can use the `title` attribute on each `


<label for="star5" title="Excellent"><span>★</span</label>
<label for="star4" title="Very Good"><span>★</span</label>
<label for="star3" title="Average"><span>★</span</label>
<label for="star2" title="Poor"><span>★</span</label>
<label for="star1" title="Very Poor"><span>★</span</label>

This provides screen reader users with context about the rating.

5. Adding CSS Variables (Optional)

To make the component more customizable and maintainable, let’s use CSS variables. We can define variables for the star color and size.


.star-rating {
  --star-color: #ccc;
  --star-hover-color: #ffc107;
  --star-size: 2em;
  display: inline-flex;
  direction: rtl;
  font-size: var(--star-size);
}

.star-rating input {
  display: none;
}

.star-rating label {
  color: var(--star-color);
  cursor: pointer;
  transition: color 0.2s ease;
}

.star-rating label:hover, .star-rating label:hover ~ label {
  color: var(--star-hover-color);
}

.star-rating input:checked ~ label {
  color: var(--star-hover-color);
}

Now, you can easily change the star color or size by modifying the CSS variables.

Common Mistakes and How to Fix Them

Here are some common mistakes and how to fix them:

  • Incorrect HTML Structure: Make sure your HTML structure is correct, with each star represented by a radio input and a label. Ensure that the `for` attribute of the label matches the `id` of the input.
  • Incorrect CSS Selectors: Double-check your CSS selectors. The `~` (general sibling combinator) is crucial for the hover effect to work correctly. Also, make sure that the `direction: rtl` is applied to the main container.
  • Forgetting `display: none` for the inputs: The radio inputs are hidden because they are not needed for visual representation.
  • Not Using Transitions: Transitions make the animation smooth. Ensure you’ve added a transition to the `color` property of the label.
  • Misunderstanding the `~` Selector: The `~` selector selects all sibling elements that follow the selected element. In our case, it selects all labels that follow the hovered or checked label.
  • Not Considering Accessibility: Always include the `title` attribute on the labels to provide context for screen reader users.

Adding a Reset Button (Optional)

You might want to add a reset button to clear the selected rating. Here’s how you can do that:

  1. Add a reset button to your HTML:

<button type="reset" class="reset-button">Reset</button>
  1. Add some CSS to style the reset button:

.reset-button {
  margin-top: 10px;
  padding: 5px 10px;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
}

.reset-button:hover {
  background-color: #ddd;
}
  1. Add the reset button functionality. You can use JavaScript to reset the radio button selection. Here’s how to do that:

const resetButton = document.querySelector('.reset-button');

resetButton.addEventListener('click', () => {
  const radios = document.querySelectorAll('input[name="rating"]');
  radios.forEach(radio => radio.checked = false);
});

Key Takeaways

  • Use radio inputs to create a star rating component, ensuring only one rating can be selected.
  • Use CSS pseudo-classes (`:hover`, `:checked`) to create interactive effects.
  • The `~` (general sibling combinator) is key to the hover effect.
  • CSS variables improve maintainability and customization.
  • Always consider accessibility by providing descriptions for screen readers.

Frequently Asked Questions (FAQ)

  1. Can I customize the star symbol? Yes, you can change the star symbol by modifying the content of the `span` element in the HTML. You can use any Unicode character.
  2. How can I change the star color? You can change the star color by modifying the `color` property in the `.star-rating label` and `.star-rating label:hover` CSS rules. If you’re using CSS variables, modify the `–star-color` and `–star-hover-color` variables.
  3. How do I make the rating persistent? This example uses only CSS and HTML. To make the rating persistent, you’ll need to use JavaScript to save the selected rating (e.g., in local storage or by sending it to a server).
  4. How can I add a different animation? You can experiment with different CSS transitions or animations on the label element to achieve different visual effects. For instance, you could add a scale transform on hover.
  5. How do I make the component responsive? You can make the component responsive by using relative units (e.g., `em`, `rem`, or percentages) for the font size and padding. Also, consider using media queries to adjust the size and layout for different screen sizes.

This CSS star rating component is a simple yet powerful example of what you can achieve with CSS. By understanding the core concepts and following these step-by-step instructions, you can create interactive and visually appealing components for your websites. Remember to experiment, customize, and adapt the code to fit your specific needs. With each project, you’ll deepen your understanding of CSS and become a more proficient web developer. The ability to create engaging user interfaces is crucial in today’s digital landscape, and mastery of CSS is a vital skill. This project provides a solid foundation for further exploration into more advanced CSS techniques and interactive web development. Embrace the learning process, and enjoy the journey of creating beautiful and functional web experiences.