Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 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.

See Question&Answers more detail:os

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...