Search code examples
htmltextwrapperbreakcpu-word

How to Wrap text in span and not breaking words?


I have a small code that wraps text in span. The problem is that the wrap doesn't consider the white spaces to change the line and break the words in the middle.

The span text is for a function that animates letters independently, that's the reason for the inline-block.

JS:

        $('.text').html(function (i, html) {
            var chars = $.trim(html).split("");
            return '<span>' + chars.join('</span><span>') + '</span>';
        });

CSS:

    .text span {
        display: inline-block;
        min-width: 15px;
    }

Solution

  • Each inline-block is treated as its own word. To make words stick together you could wrap each word in another span for example like this:

    $('.text').each((i, e) => {
      const element = $(e);
      element.html(element.text().split(' ').map(word => {
        const letters = (word + ' ').split('').map(char => '<span>' + char + '</span>');
        return '<span class="word">' + letters.join('') + '</span>';
      }).join(''));
    });
    
    .text .word {
      display: inline-block;
    }
    

    Or, if all you need are just spaces between letters, you can achieve it using letter-spacing and word-spacing