Skip to content Skip to sidebar Skip to footer

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.

https://jsfiddle.net/jcwjptu8/

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:

functionchangeWidth()
{
    $("#hp").css("width","10%");
}

functionreset()
{
  $("#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, #C7D9F830px);
	left: 5%;
	transition: all 1s;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script><divid="cont"><divid="hp"></div></div><buttononclick="changeWidth()"> Run</button><buttononclick="reset()"> Reset</button>

Post a Comment for "Fixed Background Gradient With Dynamic Width"