Search code examples
javascripthtmlcsskerningletter-spacing

Is it possible to have different letter-spacing between characters in the same word? Can this be accomplished with CSS only?


I've done some research, and I'm aware of the letter-spacing CSS property, but is it possible to have different characters within the same word spaced differently?

I wouldn't be skipping any layers, so I couldn't accomplish this with using span tags every two letters.

.ex      { letter-spacing: -2.0px }
.am      { letter-spacing: -1.5px }
.pl      { letter-spacing: -1.0px }
.e       { letter-spacing: -0.5px }
<span class="ex">Ex</span><span class="am">am</span><span class="pl">pl</span><span class="e">e</span>

The functionality I'm looking for would be more like this, but I'm not sure it's possible:

.ex      { letter-spacing: -2.0px }
.am      { letter-spacing: -1.5px }
.pl      { letter-spacing: -1.0px }
.e       { letter-spacing: -0.5px }
<kern class="1">E<kern2 class="2">x</kern><kern3 class="3">a</kern2><kern4 class="4">m</kern3><kern5 class="5">p</kern4><kern6 class="6">l</kern5>e</kern6>

I appreciate any feedback, thanks!


Solution

  • Yes you can.

    I used a jQuery function to wrap every letter in a span. Then by using span:nth-child(x) you can all give them different negative left-margins.

    $(function() {
            var words = $('p').text().split("");
            for (i in words)
                words[i] = '<span>' + words[i] + '</span>';   
            var text = words.join('');
            $("p").html(text);
    });
    p {
        font-size: 3em;
    }
    span {
        border: 1px solid red;
        margin-left: -5px;
    }
    span:nth-child(4) {
        margin-left: 15px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>Example</p>

    EDIT

    If you want to set a margin per letter, you could use this. I now only defined the letters of the word 'example', but I think you'll get the point.

    $(function() {
        var abc = {e:'-5px', x:'-5px', a:'-5px', m: '15px', p:'-5px', l:'-5px'};
        
        var words = $('p').text().split("");
        for (i in words)
            words[i] = '<span style="margin-left: '+abc[words[i]]+'">' + words[i] + '</span>';   
        var text = words.join('');
        $("p").html(text);
    });
    p {
        font-size: 3em;
    }
    span {
        border: 1px solid red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>Example</p>