Why isn´t my top span coloring until covering the whole given width?

Viewed 37

Using the code provided in this link Convert a decimal rating (max of 5 w/ 0.1 increments) to a percentage, I'm implementing an star rating system. The problem is that the starts are only filling whole numbers. For example, if my number is 2.3 the orange stars only fill until 2 even though its width is being given correctly taking into account the 0.3.

HTML

 <div class="star-container">
     <span class="star-icon grey" [innerHTML]="icons"></span>
     <span
          class="star-icon orange"
          [ngStyle]="getCssWidth()"
          [innerHTML]="icons"
          ></span>
  </div>

CSS

  .star-container {
  max-width: 140px;
  width: 85px;
  height: 20px;
  line-height: 20px;
  display: inline-block;
  }

  .star-container .star-icon {
  font-size: 20px;
  position: relative;
  }

 .star-container .star-icon.orange {
  color: #f37a1f;
  top: -22px;
  display: block;
  height: 100%;
  overflow: hidden;
  }

  .star-container .star-icon.grey {
   color: #e3e3e3;
  }

  .star-container:not(:last-child) {
   margin-right: 5px;
  }

Typescript

   cssWidth: number = 0;
   icon = "&#9733;";
   icons = `${this.icon}${this.icon}${this.icon}${this.icon}${this.icon}`;

   ngOnInit() {
     this.calculateCssWidth();
   }

   public getCssWidth() {
   let styles = {
      width: `${this.cssWidth.toString()}px`
   };
      return styles;
   }

   calculateCssWidth() {
      let num = 2.7; //Number of stars
      this.cssWidth = this.getStars(num);
   }

   getStars(num) { 
      return (num / 5) * 85;
   }

This image show how it is supposed to look

This one shows how it actually looks

As you can see, even though the second span in the html does receive the correct width, it does not color to the end, instead it just fills it if it can fill the whole stars.

1 Answers

First I believe there is a typo in your CSS as you are missing a period from the first line of CSS if the intention is that this is a class and not an element.

Second I think the math is wrong for the getStars. Changing this value to 100 gets things to work as expected in this stackbliz.

So change CSS to:

.star-container {
  max-width: 140px;
  width: 85px;
  height: 20px;
  line-height: 20px;
  display: inline-block;
  }

and adjust your getStars function:

getStars(num) {
    return (num / 5) * 100;
  }

EDIT BASED ON COMMENT:

The root cause of your issue is that while you have defined your container component as 85px, your sub-components are in fact 100px due to total width of icons.

enter image description here

If your intention is to make the width dynamic you are better off using percentages as discussed in the thread you reference in your question.

Related