How To Create Rainbow Text in HTML & CSS & JavaScript

2011/12/02

Rainbows are amazing things. They are just so colorful.

I’m sure many people would like to use them in their web applications. They make wonderful backgrounds, logos, but I think they are especially cool in texts.

There are basically three ways to create rainbow texts for web application.

1. With image editor

Almost any image editor is capable of this. Gimp, Pixelmator, Photoshop. Just create a text and apply gradient for it. Then you just

<img src="rainbowtext.png"/>

However, it has two big problems: the text won’t be searchable and the text will be difficult to change.

In other words, let’s NOT use it.

2. Separate elements

This is the straightforward way. It means wrapping each letter in it’s own element.

<span style="color:#f00">R</span>
<span style="color:#f50">a</span>
<span style="color:#ff0">i</span>
<span style="color:#5f0">n</span>
...

Rain

As you can see, it’s definitely NOT meant to be done manually. Basically you need to write some javascript to generate the codes. We’ll take a look into that later.

3. Background image + CSS magic

This is the “best” way because text will be easy to read and modify after you hide the style to .css file.

.rainbow {
  background-image:-webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );
  color:transparent;
  -webkit-background-clip: text;
}

And now you can do:

<span class="rainbow">Rainbows are colorful and scalable and lovely</span>


Rainbows are colorful and scalable and lovely

This method works without JavaScript (which is always a positive thing). It’s also the clearest because it’s just few simple lines of CSS.

Note: If you use this in other than span (or other display:inline) element, it will spread the spectrum across the whole width, making it not so rainbowish. For example:

<div class="rainbow">Not rainbow!</div>
Not rainbow!

You can get around this with span element:

<div><span class="rainbow">Colorful rainbow.</span></h2>
Colorful rainbow.

But… there’s this one bad point: All browsers do not support webkit! (actually the only ones that do are chrome and safari)

Since we need this to run perfectly in all browsers, we need…

THE ULTIMATE RAINBOW SOLUTION!

Use CSS if browser has webkit, use JavaScript if not.

This means using both methods, 2 and 3.

So here’s how to achieve it. First we need JavaScript to to get the colors.

function color_from_hue(hue)
{
  var h = hue/60;
  var c = 255;
  var x = (1 - Math.abs(h%2 - 1))*255;
  var color;
 
  var i = Math.floor(h);
  if (i == 0) color = rgb_to_hex(c, x, 0);
  else if (i == 1) color = rgb_to_hex(x, c, 0);
  else if (i == 2) color = rgb_to_hex(0, c, x);
  else if (i == 3) color = rgb_to_hex(0, x, c);
  else if (i == 4) color = rgb_to_hex(x, 0, c);
  else color = rgb_to_hex(c, 0, x);
 
  return color;
}
 
function rgb_to_hex(red, green, blue)
{
  var h = ((red << 16) | (green << 8) | (blue)).toString(16);
  // add the beginning zeros
  while (h.length < 6) h = '0' + h;
  return '#' + h;
}

This has some mysterious looking HSL conversion math behind it. If you are interested about the details, check what Wikipedia says about converting HSL to RGB.

But I guess you aren’t.

Next, we should wrap this into jQuery to make it easy to use.

(function( $ ) {
 
  $.fn.rainbowize = function() {
    return this.each(function() {
      var rainbowtext = '';
      var hue=0;
      var step=0;
 
      // get the current text inside element
      var text = $(this).text();
 
      // hue is 360 degrees
      if (text.length > 0)
        step = 360 / (text.length);
 
      // iterate the whole 360 degrees
      for (var i = 0; i < text.length; i++)
      {
        rainbowtext = rainbowtext + '<span style="color:' + color_from_hue(hue) + '">' + text.charAt(i) + '</span>';
        hue += step;
      }
 
      $(this).html(rainbowtext);
    });
  };
})( jQuery );

Then to the CSS, we add rainbowize class for webkit browsers.

.rainbowize {
  background-image:-webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );
  color:transparent;
  -webkit-background-clip: text;
}

And finally connect everything to document’s ready function.

$(document).ready(function() {
    if( $.browser.webkit )
       $(".rainbow").addClass("rainbowize");
    else
       $(".rainbow").rainbowize();
});

Now, whenever you write something like

<span class="rainbow">I love rainbows because they are so colorful and pretty!</span>

it will show up as “I love rainbows because they are so colorful and pretty!” and be rainbow colored beautifully in any browser!

Lovely.

{ 4 comments… read them below or add one }

jayjfadd June 8, 2012 at 20:13

Sweet stuff!

Reply

Justin June 30, 2012 at 21:14

Hey, I’m trying to utilize your code in a website I’m rewriting for my school but I’m still pretty new to html/css/JS and I’m having trouble figuring out how to organize all the code above. I’ve got an external CSS file that I tried putting the given css code in, and then made an external JS file to hold all the JS code. Could you possibly help?

Thanks so much for posting this, the css works great in Chrome and looks awesome, I just know this site will be used by other browsers

Justin

Reply

Andri August 25, 2012 at 22:17
grmbl March 22, 2013 at 07:39

Nice, simple and effective. Thanks for sharing! +fav

Reply

Leave a Comment

Previous post: