'Why wrapping words in span changes the text width?

In my application, I'm wrapping each word and whitespace with span tags. I do this on the fly, i.e. when the user loads the page I parse the content and wrap the words/whitespace. Pre-processing the HTML is not possible, because the amount of text can be big, and wrapping every single word/whitespace with span tags causes performance issues especially when running on mobile devices.

The problem is that wrapping word/whitespaces with span tags causes a slight change in the text width, which sometimes results in a word being shifted to the next line (an undesired behavior).

I have a sample code below, why the total width is different in these two cases (wrapping words/whitespaces with span tags VS plain text node)? Any way of accomplishing this without the text width being changed?

const width1 = document.querySelector("body > p:nth-child(1) > span").getBoundingClientRect().width;
const width2 = document.querySelector("body > p:nth-child(2) > span").getBoundingClientRect().width;

document.querySelector('#result').appendChild(document.createTextNode(`Difference in widths: ${width1 - width2}px`));
<p><span><span>This</span> phase</span></p>

<p><span>This phase</span></p>

<div id="result" />


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source