Skip to content

Instantly share code, notes, and snippets.

@marcomontalbano
Last active January 16, 2020 13:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcomontalbano/ad353132ce5f013c84be7c30565f8980 to your computer and use it in GitHub Desktop.
Save marcomontalbano/ad353132ce5f013c84be7c30565f8980 to your computer and use it in GitHub Desktop.
How to create a progress bar that changes its background-color dynamically using css variables. https://jsfiddle.net/gh/gist/library/pure/ad353132ce5f013c84be7c30565f8980

CSS Variables (and progress bar)

example here: https://jsfiddle.net/gh/gist/library/pure/ad353132ce5f013c84be7c30565f8980

CSS variables are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g. --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);) .

https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables

Progress Bar

You can change the progress bar percentage changing the --percentage variable directly on the style attribute.

The background-color will change accordingly from green to red.

/* 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;
}
<div class="progress">
<div style="--percentage: 33;"></div>
</div>
// this is just for demo, you can remove it.
setInterval(function() {
document.querySelector('.progress > div')
.setAttribute('style', '--percentage: ' + parseInt(Math.random() * 100));
}, 1500);
name: css-variables
description: How to create a progress bar that changes its background-color dynamically using css variables.
authors:
- Marco Montalbano
wrap: b
panel_js: 0
panel_css: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment