Search code examples
cssbackground-colorlinear-gradients

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


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);
}

Solution

  • 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.