Blocky gradient effect in CSS3

This can be achieved using linear-gradient. Setting multiple colors to the gradient can be done by assigning multiple color stops and the blocky effect can be achieved by making the next color start at the exact same place where the current color ends (that is, same stop percentage for the current color’s end position and the next color’s start position).

In standards compliant browsers, the following is the only line of code that would be needed:

background: linear-gradient(to right, green 20%, 
                            yellowgreen 20%, yellowgreen 40%, 
                            yellow 40%, yellow 60%, 
                            orange 60%, orange 80%, red 80%);

However, in-order to produce a similar effect in older browser versions, we have to include the vendor prefixed versions also.

div {
  height: 20px;
  width: 450px;
  background: -webkit-gradient(linear, 0 0, 100% 0, color-stop(0.2, green), color-stop(0.2, yellowgreen), color-stop(0.4, yellowgreen), color-stop(0.4, yellow), color-stop(0.6, yellow), color-stop(0.6, orange), color-stop(0.8, orange), color-stop(0.8, red));
  background: -webkit-linear-gradient(to right, green 20%, yellowgreen 20%, yellowgreen 40%, yellow 40%, yellow 60%, orange 60%, orange 80%, red 80%);
  background: -moz-linear-gradient(to right, green 20%, yellowgreen 20%, yellowgreen 40%, yellow 40%, yellow 60%, orange 60%, orange 80%, red 80%);
  background: -o-linear-gradient(to right, green 20%, yellowgreen 20%, yellowgreen 40%, yellow 40%, yellow 60%, orange 60%, orange 80%, red 80%);
  background: linear-gradient(to right, green 20%, yellowgreen 20%, yellowgreen 40%, yellow 40%, yellow 60%, orange 60%, orange 80%, red 80%);
}
<div></div>

For IE 9 and lower, we would have to use filters like mentioned in this CSS Tricks article because they don’t support linear-gradient.

Can I Use – Linear Gradients

Leave a Comment