'Generate solid colors using CSS linear-gradient (not smooth colors)

Assuming my linear CSS gradient looks like this:

background: linear-gradient(to right, red 0%, green 20%, blue 40%, purple 60%, yellow 80%, black 100%)

It will generate a CSS gradient that looks like this:

enter image description here

How do I make the same gradient but with solid colors without the transitioning between the colors? (using CSS)

Something similar to this:

enter image description here Thanks



Solution 1:[1]

Like this

.gradient {
  width: 500px;
  height: 200px;
  background: linear-gradient(to right, 
      red    20%, 
      green  20%, 
      green  40%, 
      blue   40%, 
      blue   60%, 
      purple 60%, 
      purple 80%, 
      yellow 80%,
      yellow 100%
  );
}
<div class="gradient"></div>

Solution 2:[2]

Gradient is created through blending of colors. You can control the blending effect of colors by specifying range for each color like in below example of .flag. In .flag:

  1. the color #00ae00 will be applied till 33.3% of the div
  2. from that point till 66.6%, white will be applied
  3. in the end orange will start from 66.6% till the end of the box

This way you can add as many colors as you want.

But one thing keep in mind, it looks fine when the degree is straight, if you change the angle, in some cases edges of colors may not look smooth (depends upon color and screen density) as you can see in .pixeleted

.flag{
  background: linear-gradient(to right, #00ae00 33.3%, white 33.3%, white 66.6%, orange 66.6%);


margin-right: 20px;
}

.pixeleted{
    background: linear-gradient(30deg, red 33.3%, black 33.3%, black 66.6%, red 66.6%);
}
    
div {
  width: 290px;
  height: 145px;
  border: 2px solid #999;
  display: inline-block;
}
<div class="flag"></div>
<div class="pixeleted"></div>

Solution 3:[3]

you don't have to repeat the colors. It's also possible to write it like this:

background: linear-gradient(to right, 
      red    20%, 
      green  0 40%,
      blue   0 60%,
      purple 0 80%,
      yellow 0 100%
  );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Jakub Kurdziel