Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any clean CSS method to make each letter in a word a different color?

Tags:

css

colors

I need a way to allow each letter of a word to rotate through 3 different colors. I know of some not so clean ways I can do this with asp.NET, but I'm wondering if there might be a cleaner CSS/JavaScript solution that is more search engine friendly.

The designer is including a file like this for each page. I'd rather not have to manually generate an image for every page as that makes it hard for the non-technical site editors to add pages and change page names.

like image 279
EfficionDave Avatar asked Sep 30 '08 23:09

EfficionDave


People also ask

How do you make each letter a different color in CSS?

This is the easiest way of creating such kind of text. Put your text in a <span> tag and give it a class name "multicolortext". Then, you need the CSS background-image property to add a gradient background to your text with its "linear-gradient" value, where you put the names of your preferred colors.

How do I make one word a different color in CSS?

To colored just one word you can use <span style="your style"> WORD</span> . This way you don't have to style the whole paragraph. Example: <p> The quick brown <span style="color: brown">fox</span> jumps over... </p> .

How do you style individual letters in CSS?

In order to style something in CSS, you need a selector to target it. If you're going to style individual letters, you need to wrap each one in an HTML element so that you can then select it in CSS.


3 Answers

Here is some JavaScript.

var message = "The quick brown fox.";
var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, blue

for (var i = 0; i < message.length; i++){
  document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "</span>");
}
like image 188
Ryan Rodemoyer Avatar answered Oct 17 '22 08:10

Ryan Rodemoyer


There’s definitely no solution using just CSS, as CSS selectors give you no access to individual letters (apart from :first-letter).

like image 41
Paul D. Waite Avatar answered Oct 17 '22 09:10

Paul D. Waite


On the server-side you can do this easily enough without annoying search engines AFAIK.

// This server-side code example is in JavaScript because that's
// what I know best.
var words = split(message, " ");
var c = 1;
for(var i = 0; i < words.length; i++) {
   print("<span class=\"color" + c + "\">" + words[i] + "</span> ");
   c = c + 1; if (c > 3) c = 1;
}

If you really want dead simple inline HTML code, write client-side Javascript to retrieve the message out of a given P or DIV or whatever based on its ID, split it, recode it as above, and replace the P or DIV's 'innerHTML' attribute.

like image 28
Brendan Kidwell Avatar answered Oct 17 '22 09:10

Brendan Kidwell