محمد الشماسين محمد الشماسين - 3 months ago 32
CSS Question

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 :

img1

the width will decrease as the HP decrease.

the problem is that i want the background to maintain its gradient as the width change, like when the width reach 10px i want just the red color to stay, eg:

img2

is there any way to do that using css ??

Note: i'm using absolute position for the bar, and it's a child of a big parent div.
Note 2 : i'm using percentage value for width and height for all of the element, put these absolute value is what should be for a document with 1366 width and 670 height .

Snippet :



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 left, #C7D9F8 60%, red);
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>




Answer

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>