thomasfrank.se

Create text color gradients

July 20, 2006

We have seen color gradiented backgrounds on the web for some time now. But here's a new effect for you -- color gradiented text. I've made a small script (3 kB) that lets you use gradients on your text. It is unobtrusive and really simply to use, no images needed.

An example

Here is an example to get you started:
A gradiented headline
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam interdum tincidunt eros. Sed dictum, odio accumsan consequat fermentum, mauris diam faucibus pede, ac ultrices libero metus non risus. Aliquam id eros. Nullam tortor elit, interdum at, adipiscing sed, interdum nec, tellus.

Headline start color:     end color  
Body start color:           end color     

How do I know the hex values of colors?

You use hexadecimal numbers to set the color values. If you are not sure how this works you can find some values to start off with here.
Most image editing programs will show hexadecimal color values in their color pickers.

Apply the script

To use this script you will need to download it and embed in the head section of your page.
<head>
<script type="text/javascript" src="gradientText.js"></script>
...
</head>

Set your gradients directly in the html code

The easiest way to use the script is to set your gradients directly in the html code. It is done like this:
<h1><span class="gradient_1A48A5_559BBB">
A gradiented headline
</span></h1>
<span id="myBodyText"><span class="gradient_000_666">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam interdum 
tincidunt eros. Sed dictum, odio accumsan consequat fermentum, mauris diam 
faucibus pede, ac ultrices libero metus non risus. Aliquam id eros. 
Nullam tortor elit, interdum at, adipiscing sed, interdum nec, tellus. 
</span></span>

As you can see you simply wrap the text you want to apply a gradient to inside a span tag with the class name gradient_startColor_endColor.

Set/change the gradients using JavaScript

To set or change the gradients using JavaScript is not complicated either -- you use the following syntax:
Here is an example that will change the gradient of all h1-tags:
htmlElements=document.getElementsByTagName('h1');
gradientText.set(htmlElements,'a51a41','e4a253');

You could just as well find your html elements by id or by class. That's up to you.
For those JavaScripters who generate a lot of content dynamically:

Happy gradienting!
[comments]