Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

html - Change last letter color

Example code:

<p class="test">string</p>

I want to change the color on the last letter, in this case "g", but I need solution with css, I don't need a javascript solution.

I display the string letter by letter and i cant use static solution.

question from:https://stackoverflow.com/questions/15441742/change-last-letter-color

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...