Change last letter color

Everyone says it can't be done. I'm here to prove otherwise.

Yes, it can be done.

Okay, so it's a horrible hack, but it can be done.

We need to use two CSS features:

  • Firstly, CSS provides the ability to change the direction of the flow of the text. This is typically used for scripts like Arabic or Hebrew, but it actually works for any text. If we use it for English text, the letters are displayed in reverse order to how the appear in the markup. So to get the text to show as the word "String" on a reversed element, we would have to have markup that reads "gnirtS".

  • Secondly, CSS has the ::first-letter pseudo-element selector, which selects the first letter in the text. (other answers already established that this is available, but there's no equivalent ::last-letter selector)

Now, if we combine the ::first-letter with the reversed text, we can select the first letter of "gnirtS", but it'll look like we're selecting the last letter of "String".

So our CSS looks like this:

div {
    unicode-bidi:bidi-override;
    direction:rtl;
}

div::first-letter {
    color: blue;
}

and HTML:

<div>gnirtS</div>

Yes, this does work -- you can see the working fiddle here: http://jsfiddle.net/gFcA9/

But as I say, it is a bit hacky. And who wants to spend their time writing everything backwards? Not really a practical solution, but it does answer the question.


Use ::after pseudo-element combined with attr() function:

p::after {
    content: attr(data-end) ;
    color: red ;
}
<p data-end="g">Strin</p>

p::after {
  content: attr(data-end) ;
  color: red ;
}
<p data-end="g">Strin</p>

Another solution is to use ::after

.test::after{
    content: "g";
    color: yellow;
}
<p class="test">strin</p>

This solution allows to change the color of all characters not only letters like the answer from Spudley that uses ::first-letter. See ::first-letter specification for more information. ::first-letter applies only on letters it ignores punctuation symbols.

Moreover if you want to color more than the last character you can :

.test::after{
     content: "ing";
     color: yellow;
}
<p class="test">str</p>

For more information on ::after check this link.


Without using javascript, your only option is:

<p class="test">strin<span class="other-color">g</span></p>

Edit for your fiddle link:

I'm not really sure why you said you didn't need a javascript solution, since you have quite a bit of it already. Regardless, in this example, you need to make only a couple small changes. Change line 10 from

elem.text(elem.text() + contentArray[current++]);

to

if ( current == contentArray.length-1 ) {
    elem.html(elem.html() + "<span style='color:red'>"+contentArray[current++]+"</span>");
} else {
    elem.html(elem.html() + contentArray[current++]);
}

Note that it's important to use .html() instead of .text() now, since there's actually HTML markup being inserted.

Working fiddle: http://jsfiddle.net/QTUsb/2/