css-variables

How to create a progress bar that changes its background-color dynamically using css variables. author(s): Marco Montalbano

HTML

<div class="progress">
  <div style="--percentage: 33;"></div>
</div>

CSS

/* GitHub Gist available here: https://gist.github.com/marcomontalbano/ad353132ce5f013c84be7c30565f8980 */

.progress {
  background: #efefef;
  height: 26px;
  border-radius: 20px;
  overflow: hidden;
}

.progress > div {
  --percentage: 0;
  width: calc(var(--percentage) * 1%);
  height: 100%;
  background-color: hsl(calc(120 - var(--percentage) / 100 * 120), 38%, 62%);
  border-radius: 4px;
  transition: width .8s, background-color .8s;
}

JavaScript

// this is just for demo, you can remove it.

setInterval(function() {
	document.querySelector('.progress > div')
    .setAttribute('style', '--percentage: ' + parseInt(Math.random() * 100));
}, 1500);