rimas
rimas

Reputation: 757

Is it possible to apply different styles to different letters in word?

Lets say, I have word 'Test'. Is it possible to make lets say, first letter(T) red, second(e) - green and bold and last(t) - just bold? I can break word on symbols and apply different styles but maybe I can do it without splitting?

Upvotes: 3

Views: 1003

Answers (4)

dotthor
dotthor

Reputation: 68

I guess is now safe to use css highlight api for such a case, like:

const node = document.getElementById("test");

    const firstLetter = new Range();
    firstLetter.setStart(node.childNodes[0], 0);
    firstLetter.setEnd(node.childNodes[0], 0 + 1);

    const secondLetter = new Range();
    secondLetter.setStart(node.childNodes[0], 1);
    secondLetter.setEnd(node.childNodes[0], 1 + 1);

    const lastLetter = new Range();
    lastLetter.setStart(node.childNodes[0], 3);
    lastLetter.setEnd(node.childNodes[0], 3 + 1);

    CSS.highlights.set("first-letter", new Highlight(firstLetter));
    CSS.highlights.set("second-letter", new Highlight(secondLetter));
    CSS.highlights.set("last-letter", new Highlight(lastLetter));
::highlight(first-letter) {
        color: red;
        background-color: aqua;
    }

    ::highlight(second-letter) {
        color: green;
        font-weight: bold;
        background-color: blueviolet;
    }

    ::highlight(last-letter) {
        font-weight: bold;
        background-color: chocolate;
    }
<span id="test" style="font-size: 3rem;">Test</span>

Upvotes: 0

Roel_P
Roel_P

Reputation: 78

The very long way: example: http://jsfiddle.net/9a9GM/

Html

    <ul>
<li class='t'>T</li><li class='e'>e</li><li class='s'>s</li><li class='t2'>t</li>
    </ul>

css

li
{
    display:inline;
    font-size: 20px;
    padding-right: 1px;
}

.t{ color:red;}
.e{ color:blue;}
.s{ color:pink;}
.t2{ color:green;}

Upvotes: 0

Rudie
Rudie

Reputation: 53821

No. Some browsers implement :first-letter (not all), but there's no such thing as :nth-letter(2) or the like.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

You can apply a specific colour, and style, to the :first-letter of an element, but beyond that: no, this isn't possible without JavaScript; unless each letter (or pair of letters) is wrapped in its own element.

div {
    color: black;
}

div:first-letter {
    color: red;
}

JS Fiddle demo, using :first-letter.

Upvotes: 9

Related Questions