Phreak Phreak - 1 month ago 9
CSS Question

CSS partial color percentage value

I'm trying to show a percentage value with circles trying to create the image below with code. I'll get the percentage value from the HTML. I'm just not sure how to partially color the circle with css.

Percent progress with color

<div class="meter" data-attr="50%">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>

.meter {
span {
display: inline-block;
width: 25px;
height: 25px;
border-radius: 50%;
border: 1px solid red;
}
}

<script>
var circlePrecent = 50%;
</script>


https://jsfiddle.net/j8of7yag/

Answer

Use a basic background color, and cover it with linear gradient. Control the linear gradient's size using backgroundSize in js:

  background: #AB9E95 linear-gradient(to right, #9F1F63 0%, #9F1F63 100%) no-repeat;

Working demo:

colorCircles('65%');

setTimeout(function() {
  colorCircles('37%');
}, 1000);

function colorCircles(percentage) {
var value = parseInt(percentage, 10);

var circles = Array.from(document.querySelectorAll('.meter > span'));

var fullCircles = Math.floor(value / 20);

var partialCircle = (value % 20) / 20 * 100;

circles.forEach(function(circle, index) {
	var backgroundSize = '0% 100%';
  
	if(index < fullCircles) {
  	backgroundSize = '100% 100%';
  } else if (index === fullCircles) {
  	backgroundSize = partialCircle+'% 100%';
  }
  
  circle.style.backgroundSize = backgroundSize;
})
}
.meter {
  display: inline-block;
  box-sizing: border-box;
}

span {
  display: inline-block;
  left: 0;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  border: 1px solid red;
  background: #AB9E95 linear-gradient(to right, #9F1F63 0%, #9F1F63 100%) no-repeat;
  transition: background-size 0.3s;
}
<div class="meter">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

Comments