Search code examples
htmlcsswhitespacefont-size

spaces and   do not have the same width?


I have a div and a textarea exactly overlapped, I type in the textarea and that text is converted to spans that have varying text colors (syntax highlighting) and are then shown in the div, so it looks like you're typing in the div, but you're actually typing in the transparent textarea. At the moment I simply put a space between the spans where a space exists in the text input, but if I add more spaces in series it doesn't work (only one will show). So I tried using   instead of spaces but I was surprised to find out the width of it is different from regular spaces. What is the point of   then?

To the point, how can I add spaces that have the same width as regular spaces if   doesn't?

And here's an example of what should be two exactly matching lines (but aren't).

<span>Hello</span> <span>World</span>
<span>Hello</span>&nbsp;<span>World</span>

Note: I'm using the font "FontinSmallCaps", it's possible that's the reason for the discrepancy, but I am not willing to do away with it. Would rather filter the user input to never have two consecutive spaces. Although that would be a last resort.

If anything is unclear or needs elaboration, let me know. Thanks in advance!


Solution

  • Not exactly sure of your HTML structure, but whatever wraps the HTML you have shown could have white-space: pre set, then the spaces will all remain. No need to convert them.

    <div style="white-space:pre"><span style="white-space: pre;">Hello</span>      <span>World</span></div>