CodeCraft Chronicles

CSS: Star Rating

Learn how to create a simple star rating look with only CSS and minimum HTML. We are going to use the data attribute and the before and after selectors. Check this step-by-step guide.

Let´s Start.

GOAL

Create a rating system using minimum markup.

HTML

In orther to specify a rating we will use a span with a data attribute and a value from 1 to 5.

<span class="star" data-rating="3"></span>

CSS

The whole purpose of this snippets it´s to try to practice selectors and how can we use CSS to represent information from a data attribute.

The Content

We are going to use the character for our rating system.

  1. ★★★★

  2. ★★★★★

  3. ★★★★★

  4. ★★★★

  5. ★★★★★

The Logic

If you think about it we are always to show five stars, some will be , and others .

In orther to show both types we will use the ::before () and ::after () selectors.

Rating before after
1 1 4
2 2 3
3 3 2
4 4 1
5 5 0

The Code

.star[data-rating="1"]::before,
.star[data-rating="4"]::after {
  content: "★";
}
.star[data-rating="2"]::before,
.star[data-rating="3"]::after {
  content: "★★";
}
.star[data-rating="3"]::before,
.star[data-rating="2"]::after {
  content: "★★★";
}
.star[data-rating="4"]::before,
.star[data-rating="1"]::after {
  content: "★★★★";
}
.star[data-rating="5"]::before,
.star[data-rating="0"]::after {
  content: "★★★★★";
}

Example