I\'m not sure if my title coherently expressed my issue, but I\'ll explain below.
I would like to assign a different color to each character in a st
Dumb CSS only solution - where you need to put each letter into separate <span> so you can use :nth-child(2n+1)
.username span {
color: red;
}
.username span:nth-child(2n+1) {
color: blue;
}
<span class="username"><span>U</span><span>s</span><span>e</span><span>r</span><span>n</span><span>a</span><span>m</span><span>e</span></span>
OR
you can use small JavaScript like Ryan Rodemoyer suggested in this answer:
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>");
OR
maybe you're looking for something like this
This can be achieved with just CSS although only with a few caveats:
The general principle is:
This works because the letters in a monospace font take up the same amount of space (therefore you can be sure the letters will be in the correct position). By using absolute positioning the letters can be laid on top of the word set in HTML.
.username {
color: red;
font-family: monospace;
position: relative;
}
.username:after {
color: blue;
content: attr(data-descr);
left: 0;
position: absolute;
}
<div class="username" data-descr="u e n m">username</div>
JS Fiddle