当前位置:网站首页>How to create a progress bar that changes color according to progress

How to create a progress bar that changes color according to progress

2022-07-01 05:21:00 Phil Arist

Progress bar is a common function on Web pages , however , Do you know how to create a progress bar that automatically adjusts the color according to the progress ?

The effect is as follows :

The requirements are :

  • Progress in 80% and 100% Between , Please set the background color to green .

  • Progress in 60% To 80% Between , Set the background color to blue .

  • Progress in 40% To 60% Between , Set the background color to purple .

  • Progress in 20% and 40% Between , Set the background color to yellow .

  • Progress in 0% To 20% Between , Set the background color to red .

According to this requirement , Let's discuss this topic today .

01、 Create a progress bar

First , We need to create a progress bar . By using <progress> Tab create progress bar .

But in the following example , We need to use CSS Variable , And this label is inappropriate . So we use conventional div Labels and some CSS Style to create a progress bar .

The progress bar consists of two parts :

  • Containers

  • progress

To create a container , We just need to create one div Elements :

<div class="bar" style="--percent: 50;"></div>

We use CSS Variable percentage to indicate progress .

Then we can use pseudo class elements to create progress parts .

.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;}


02、 Color change

How can we achieve the effect of automatic color change ?

A trick : Set multiple background layers , Each background layer has a different color . Then we can adjust the background color indirectly by adjusting the layer .

When red and blue layers are stacked together , Red background . If we hide the red layer again , The background will turn blue .

  If we were to 5 Hierarchically linked , Make the upper layer a little shorter , We will get the following results :

 codepen Demonstration effect :https://codepen.io/bytefishmedium/pen/rNdaMYg

03、 Combine

Last , We need to merge the previous code , You can get a progress bar that can automatically adjust the color change .

Here it is , The effect of the color change progress bar I want to share with you is over , Thanks for reading .

原网站

版权声明
本文为[Phil Arist]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010515490222.html