Background gradient as two tone solid color - one color width in px
Asked Answered
C

3

6

div {
  height: 50px;
  width: 100%;
  background-image: linear-gradient(to right, white 50%, red 46px);
}

body {
  padding: 20px;
}
<div></div>

I'm trying to use linear gradients as a two tone solid color background in a div.

The div can be any width, and I would like one of the colors to have a specified width in px - and the other color to fill up whatever is left of the total width. Is that possible as all?

Like:

div {
  background-image: linear-gradient(to right, white auto, red 46px);
}
Chiquitachirico answered 24/11, 2017 at 9:33 Comment(0)
S
7

You Can simply go with:

Use the fixed background colour first then just put 0 in the second colour it will fill the rest of the div.

background: linear-gradient(to right, lightgreen 19px, darkgreen 0);

This will work fine for you.

div {
  display: inline-block;
  background: linear-gradient(to right, lightgreen 19px, darkgreen 0);
  width: 50%;
  height: 100px;
  color: white;
  text-align: center;
}
<div>
  Test
</div>

Hope this was helpfull.

Scrutiny answered 24/11, 2017 at 9:41 Comment(1)
Awesome, looks even better. Thanks.Chiquitachirico
E
3

You can try this :

Use the value needed for the first color (here 46px) and simply use a small value for the second color (between 0 and 45px). Then change the direction of the gradient depending on your needs.

div.first {
  height:100px;
  background-image: linear-gradient(to right, red 46px, blue 40px);
}

div.second {
  margin-top:10px;
  height:100px;
  background-image: linear-gradient(to left, red 46px, blue 0px);
}
<div class="first">

</div>

<div class="second">

</div>
Elis answered 24/11, 2017 at 9:36 Comment(1)
So, what if I want the red bit to be in the right side?Chiquitachirico
M
0

I think this is a nice time to use css variables, we can set a variable as a breakpoint and only have to update that one variable when moving the gradient.

div {
  --gradient-break: calc(100% - 46px);
  height: 50px;
  background-image: linear-gradient(to right, darkgreen var(--gradient-break), tomato var(--gradient-break));
}
<div></div>

You can use this method to make a Javascript controlled progress bar.

let progressCounter = 0;

setInterval(function() {
  if (progressCounter >= 100) {
    progressCounter = 0;
  } else {
    progressCounter++;
  }
  document.querySelector('.progress').style.setProperty('--gradient-break', progressCounter + "%")
}, 50)
div.progress {
  --gradient-break: 0%;
  height: 50px;
  background-image: linear-gradient(to right, darkgreen var(--gradient-break), tomato var(--gradient-break));
}
<div class="progress"></div>

I'm setting the progress percentage with document.querySelector('.progress').style.setProperty('--gradient-break',progressCounter+"%") and the css is taking care of the rest.

Hope this is helpful.

Meld answered 24/11, 2017 at 10:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.