Creating a Dynamic Color-Changing Progress Bar with CSS
Written on
Introduction to Progress Bars
Progress bars are widely utilized in web design, yet have you ever thought about how to design one that dynamically alters its color in relation to the progress made?
The visual effect can be summarized as follows:
For a progress range of 80% to 100%, the background will turn green. If the progress is between 60% and 80%, it will change to blue. Progress between 40% and 60% will yield a purple background, while a range of 20% to 40% results in yellow. Lastly, for progress from 0% to 20%, the background will be red.
In this guide, we’ll delve into the process of creating this dynamic progress bar.
Creating the Progress Bar
To begin, we need to establish a progress bar. Although the <progress> tag is frequently employed for this purpose, it is not suitable for our needs since we will be using CSS variables. Instead, we will utilize a standard <div> element along with CSS styles to construct our progress bar.
A progress bar consists of two main components: the container and the progression. We can create the container by implementing a <div> element like so:
<div class="bar" style="--percent: 50;"></div>
Here, we employ a CSS variable named --percent to represent the progress visually.
Next, we can define the progression section using a pseudo-class:
.bar {
height: 20px;
background-color: #f5f5f5;
}
.bar::before {
content: '';
display: flex;
justify-content: end;
width: calc(var(--percent) * 1%);
height: 100%;
background: #2486ff;
white-space: nowrap;
}
Here’s a demonstration of the progress bar in action:
Dynamic Color Change
So, how can we create the effect of changing colors automatically? The solution lies in cascading multiple background layers, each assigned a different color. By adjusting the visibility of these layers, we can create the desired color transitions.
For instance, if we stack a red layer atop a blue one, the visible color will be red. However, hiding the red layer will reveal the blue beneath.
By layering five colors and making the uppermost layer slightly shorter, we can achieve impressive visual effects:
Here’s a demo showcasing this effect:
Putting It All Together
Ultimately, we simply need to merge the two previous examples, resulting in a progress bar that seamlessly changes color according to its progress.
This innovative design not only enhances user experience but also adds a visually appealing aspect to your web projects.