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.

Leave a Comment