- Simple star rating with pure CSS
- Star rating widget
- Displaying average rating
- Demo
- 26 CSS Star Ratings
- Related Articles
- Author
- Links
- Made with
- About a code
- Simple Star Rating in CSS
- Author
- Links
- Made with
- About a code
- Pure CSS Star Rating Widget
- Author
- Links
- Made with
- About the code
- Simple Star Rating
- Author
- Links
- Made with
- About the code
- Pure CSS Star Ratings
- Author
- Links
- Made with
- About the code
- Star Rating
- Author
- Links
- Made with
- About the code
- Pure CSS Rating
- Author
- Links
- Made with
- About the code
- 5-Star Rating
- Author
- Links
- Made with
- About the code
- Standalone SVG CSS-only Star Rating Component
- Author
- Links
- Made with
- About the code
- Emoticon Star Rating
- Author
- Star rating на CSS со шрифтовыми иконками от font-awesome
- HTML-разметка
- CSS-стили
Simple star rating with pure CSS
A star rating is a great way to highlight user satisfaction with a product or a service. You can implement a simple star rating using only CSS, without additional assets like images, fonts, or SVGs.
In this guide, we’ll create a:
💡 NOTE: In this guide, we’ll focus only on the visual appearance of the star rating.
We will use special Unicode symbols a.k.a. html entities to keep it as simple and native as possible.
One of the benefits of using Unicode symbols is that they are treated as a font, which means you can apply font-related CSS properties like font-size and color .
Star rating widget
We will use a form with a set of checkboxes to allow users to leave ratings without using any JavaScript or 3rd party library. It will act as a widget with which users can interact.
class="star-rating"> class="radio-input" type="radio" id="star5" name="star-input" value="5" /> class="radio-label" class for="star5" title="5 stars">5 stars class="radio-input" type="radio" id="star4" name="star-input" value="4" /> class="radio-label" for="star4" title="4 stars">4 stars class="radio-input" type="radio" id="star3" name="star-input" value="3" /> class="radio-label" for="star3" title="3 stars">3 stars class="radio-input" type="radio" id="star2" name="star-input" value="2" /> class="radio-label" for="star2" title="2 stars">2 stars class="radio-input" type="radio" id="star1" name="star-input" value="1" /> class="radio-label" for="star1" title="1 star">1 star
As you can see the order of labels and checkboxes is reversed. This is done to implement the hover effect so that all starts up until the one that is hovered is selected.
Since you cannot select previous elements in CSS we’ll use the flex-direction property to reverse the order of labels and checkboxes.
.star-rating display: flex; flex-direction: row-reversed; justify-content: flex-end; >
Now that labels and checkboxes are displayed in the correct order, we’ll create our stars.
To do that we’ll hide checkboxes and set a pseudo-element with a content property equal to a star symbol (★).
.radio-input position: fixed; opacity: 0; pointer-events: none; > .radio-label cursor: pointer; font-size: 0; color: rgba(0,0,0,0.2); transition: color 0.1s ease-in-out; > .radio-label:before content: "★"; display: inline-block; font-size: 32px; >
Finally, let’s add some fancy effects so that the user can see the total number of stars on hover.
.radio-input:checked ~ .radio-label color: #ffc700; color: gold; > .radio-label:hover, .radio-label:hover ~ .radio-label color: goldenrod; > .radio-input:checked + .radio-label:hover, .radio-input:checked + .radio-label:hover ~ .radio-label, .radio-input:checked ~ .radio-label:hover, .radio-input:checked ~ .radio-label:hover ~ .radio-label, .radio-label:hover ~ .radio-input:checked ~ .radio-label color: darkgoldenrod; >
Displaying average rating
To display the total average rating we’ll use the meter tag. As the HTML Specs says:
The meter element represents a scalar measurement within a known range, or a fractional value
This tag comes with a set of attributes that determines the semantics of its gauge. In our case, it’s the min (minimum value), max (maximum value), and value (the current value).
Authors are encouraged to include a textual representation of the gauge’s state in the element’s contents, for users of user agents that do not support the meter element.
So in our case to make it more semantic and user-friendly we’ll include a short label:
Product rating: class="average-rating" min="0" max="5" value="4.3" title="4.3 out of 5 stars">4.3 out of 5
Now that we’re done with HTML, let’s apply some styling to make the meter tag look like stars.
First, we’ll need to visually hide the meter tag.
.average-rating position: relative; appearance: none; color: transparent; width: auto; display: inline-block; vertical-align: baseline; >
Next to display stars we’ll use a pseudo-element with a content property equal to the 5 star symbols.
To highlight the star percentage we’ll use the text background gradient hack. That is setting the linear-gradient property, combined with the background-clip and text-fill-color properties.
To calculate the fill area percentage we need to use the following formula:
.average-rating::before --percent: calc(4.3/5*100%); content: '★★★★★'; position: absolute; top: 0; left: 0; color: rgba(0,0,0,0.2); background: linear-gradient(90deg, gold var(--percent), rgba(0,0,0,0.2) var(--percent)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; >
Demo
The end result with complete code can be viewed on CodePen:
See the Pen Untitled by Nikita Hlopov (@nikitahl) on CodePen.
26 CSS Star Ratings
Collection of hand-picked free HTML and CSS star rating code examples. Update of July 2019 collection. 6 new items.
Related Articles
Author
Links
Made with
About a code
Simple Star Rating in CSS
Star rating system using HTML & CSS.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Pure CSS Star Rating Widget
Pure CSS star rating widget with HTML and CSS. No JavaScipt.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About the code
Simple Star Rating
HTML and CSS simple star rating.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About the code
Pure CSS Star Ratings
Compatible browsers: Chrome, Firefox, Opera, Safari
Author
Links
Made with
About the code
Star Rating
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About the code
Pure CSS Rating
Pure CSS rating via CSS custom properties as API.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About the code
5-Star Rating
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About the code
Standalone SVG CSS-only Star Rating Component
This is a CSS-only component that dynamically generates each of the SVG icons to be used as background images for each of the stars. For the rating value to be displayed, data-rating-value HTML attribute must be updated and calculated rounding every 0.25 to reflect the proper rating.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About the code
Emoticon Star Rating
Emoticon five star rating through Font Awesome in pure CSS.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Star rating на CSS со шрифтовыми иконками от font-awesome
Стояла задача добавить стар-рейтинг к форме комментариев для шаблона.
Это должны быть обычные 5 звездочек, при наведении на которые выделяются все звездочки от начала до той, на которую навели и при выборе (клике) такое состояние сохраняется. Также, конечно, нужно обеспечить передачу значения указанного рейтинга при отправке формы.
Решение делал не для конечного проекта, а для шаблона. Поэтому нужно было сделать звездочки максимально гибким для дальнейшей кастомизации. То есть изменения цвета, размера звездочек должно быть максимально легким. Под такую конфигурацию использование спрайта изображений не подходило, поэтому решил использовать шрифтовые иконки. Выбор пал на сервис Font Awesome. Там есть звездочки с названием fa-star-o — звездочка по умолчанию и fa-star — звездочка активная (при наведении и выборе).
Дальше решил подумать, как можно реализовать такую задача минимальными ресурсами, в идеале без использования javascript. В итоге все получилось и, как по мне, такое решение оптимальное для подобной задачи.
Кому лень читать дальше, можете сразу посмотреть результат тут — codepen.
HTML-разметка
Общая идея состоит в том, что мы выводим рейтинг обычными радиокнопками, что бы сохранить передачу данные через форму. Дальше прячем радиокнопки с помощью CSS, а выделять их будем с помощью клика по соседних лейблах, которые ссылаются на радиокнопку атрибутом for. Сами же лейблы мы выводим в виде иконок с сервиса Font Awesome.
В итоге HTML-разметка следующая:
Конечно, не забываем подключить шрифт Font Awesome в начале.
Очень важно сохранять порядок следования элементов input и label, при чем не помещать никаких вложенных элементов внутрь.Такая зависимость от html-разметки негативная, но это та жертва которую я посчитал уместной.
Также очень важно выводить радиокнопки в обратном порядке от 5 до 1.
CSS-стили
Первое, что нужно сделать — это спрятать радиокнопки. В результате у нас остаются только звездочки при нажатия на которые выделяется нужный радиобокс.
Второе — при наведении иконка должна изменятся на активную, при чем измениться должна не только текущая иконка, а и все иконки перед ней!
.star-rating__ico:hover:before, .star-rating__ico:hover ~ .b-star-rating__ico:before,
content: «\f005»; — это код активной иконки стар-рейтинга в шрифте Font Awesome. Иконки в этом шрифте вставляются через псевдоэлемент ::before
Третье — при клике на иконку состояние наведения должно сохраниться, то-есть активными должны быть текущая и соседние звездочки.
Добавляем к этому же правилу еще один селектор:
.star-rating__input:checked ~ .star-rating__ico:before
В результате главные стили, которые делают основную работу следующие:
.star-rating__input < display: none; >.star-rating__ico:hover:before, .star-rating__ico:hover ~ .star-rating__ico:before, .star-rating__input:checked ~ .star-rating__ico:before
Дальше нужно перевернуть звездочки в другую сторону, так как сестринский селектор выбирает соседей по направлению текста. По умолчанию слева-направо, а нам нужно наоборот.
Для решения этой задачи есть два способа: изменить направления текста для элемента star-rating указав direction: rtl или сделать элемент плавающим по правой стороне. Мне больше по душе второй вариант. Кроме этого сделав элементы внутри .star-rating плавающими мы уберем отступы между звездочками из-за которых пропадает наведение
В общем, дальше уже все обычно. Еще раз ссылка на результат codepen.
В результате у нас полноценный стар-рейтинг со шрифтовыми иконками, написанный только на HTML+СSS в котором легко изменять размеры и цвет звездочек.