Currently for reviews I use star rating that is displayed by css with background classes.
But I want to replace this by Font Awesome because a font is much sharper on high res screens.
The only problem is that the rating is defined dynamically by a width class in %.
I can not change the code into different div classes that define the width.
For example a score of 4,5 stars is displayed using the class width="80%;"
Max score is 5 stars.
It should look like this:
How can I replace this with Font Awesome stars?
See also this JSFiddle: https://jsfiddle.net/tLj2ybnu/8/
This answer includes two solutions. The first is pure CSS. You just set a class to indicate a score from 0 to 10. The second snippet is simpler and more flexible; it allows you to set a percentage in the tag itself.
In both examples I used stars from the Wingdings font, but you could use other fonts and characters or even a background image. The solution in both cases is to have a grey background of stars and a golden overlay that is clipped to the right width.
1: Predefined classes to indicate a value from 0 to 10
I think with just a bit of CSS you can simply do this. You could use a special font, but maybe Wingdings is also an option. It contains a couple of stars which you may use.
The snippet below shows that you can do this with only one element. Add the class
score
, and one of the classess0
tos10
to indicate a score from 0 to 10. Of course, instead of using::before
and::after
pseudo-elements, you could add nested spans and give the yellow one a width of 80% in the style attribute, but in my example the score element is more detached from how it is displayed, which I think is a better approach.The CSS is quite verbose, but with a preprocessor like SCSS, you can probably write this in a more compact way.
I'd choose one to ten, because you indicated you want half stars as well (which is common). By using a scale to 10, you can use integer values, which is more intuitive from a programmer perspective. You just have an integer score, which is then translated by CSS to half stars.
Of course you can do this with any symbol from any font.
2: Set the percentage straight in the tag
If you want to set the width in HTML specifically, you can't use
::before
and::after
. You'll need an actual element for that. Actually, it makes the CSS a bit easier, because you don't need to predefine the widths. The HTML also isn't very complex. The span for the score gets one anonymous sub-element that has just the width set. You can specify any width from 0 to 100%.The outer element (with the class) serves as a container, and generates the grey stars. The inner element generates the yellow stars overlaid on the grey ones.