MAINAK BHATTACHARYA
MAINAK BHATTACHARYA

Reputation: 23

change bar color dynamically

Problem Statement:

I want to create a bar which will change color based on the number i provide. The bar will go up and down with transition. For Eg: if number is 80: on hover bar will start from red and around 50 it will become light red and as it reaches 80 will be pretty much green.

As per my code i am able to acheive this by modifying the % of white. Any way by which i can send the number to css so that the linear-gradient property picks it up.

Here is my code:

.container{
    border: 4px solid black;
    width: 40px;
    height: 600px;
    background-size: 100% 200%;
    background-image: linear-gradient(white 50%,green 50%,red);
    transition: background-position 1s ease-in-out;
}

.container:hover{
    background-position: 0 100%;
}
<div class="container">
</div>

Upvotes: 1

Views: 314

Answers (1)

Jns
Jns

Reputation: 3257

There is a possibility to pass a variable value directly into your css class. You define your custom variable in css by var(--NameOfYourVar). And in your html part you can use the style property to pass a value to your variable.

.container{
    border: 4px solid black;
    width: 40px;
    height: 600px;
    background-size: 100% 200%;
    background-image: linear-gradient(white var(--myVar),green 50%,red);
    transition: background-position 1s ease-in-out;
}

.container:hover{
    background-position: 0 100%;
}
<div class="container" style="--myVar: 80%;">
</div>

But I'm not sure if this already fully supported by all browsers.

Upvotes: 1

Related Questions