Fixed Background Gradient With Dynamic Width
i'm trying to do HP bar for a soldier in a game. the bar should be 50px width and 10px for height (on initialization). it should be like this : the width will decrease as the HP d
Solution 1:
You can use absolute values in a linear-gradient
background. For example, background:linear-gradient(90deg, red 10px, blue 20px);
will give a gradient from red to blue between 10px and 20px from the left of the element regardless of the width of the element.
I've included this in a fiddle below, along with another approach that you could use to change the colour of the bar using the meter
tag.
Solution 2:
I've taken your snippet and replaced your % values on the gradient with an absolute pixel value. I've also inverted the gradient so it goes from left to right, from red to the other color. You can check that if you modify the width of the bar, the red still remains visible.
background: linear-gradient(to right, red, #C7D9F8 30px);
Full snippet below:
function changeWidth()
{
$("#hp").css("width","10%");
}
function reset()
{
$("#hp").css("width","30%");
}
#cont {width:170px; height:170px; background:#000; position:relative}
#hp {
position: absolute;
bottom: 5%;
width: 30%;
height: 10px;
background: linear-gradient(to right, red, #C7D9F8 30px);
left: 5%;
transition: all 1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="cont">
<div id="hp"></div>
</div>
<button onclick="changeWidth()"> Run</button>
<button onclick="reset()"> Reset</button>
Post a Comment for "Fixed Background Gradient With Dynamic Width"