Blocky gradient effect in CSS3

前端 未结 5 1566
后悔当初
后悔当初 2020-11-29 11:43

Is it possible to make the below gradient look more \"blocky\", so that instead of switching from green to red gradually, it\'s done in steps like the below picture?

5条回答
  •  隐瞒了意图╮
    2020-11-29 12:30

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

    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

提交回复
热议问题