The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.
For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):
#f22
at 0%
(that is the left edge of the element). First color is always assumed to start at 0%
even though the percentage is not mentioned explicitly.0%
to 14.25%
, the color changes from #f22
to #f2f
gradually. The percenatge is set at 14.25
because there are seven color changes and we are looking for equal splits.14.25%
(of the container's size), the color will exactly be #f2f
as per the gradient specified.14.25%
.So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.
.rainbow {_x000D_
background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text
.
(Note that the background-clip: text
is an experimental property and is not supported widely.)
Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:
to right
. If it should be red at right and brown at left then give the direction as to left
.red
as the first color (percentage is assumed to be 0%).50%
the color should be orange
and then the final color would be brown
. The position of the final color is always assumed to be at 100%.Thus the gradient's specification should read as follows:
background-image: linear-gradient(to right, red, orange 50%, brown).
If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.
.red-orange-brown {_x000D_
background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
color: transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
color: transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_