Search code examples
javascripthtmlreactjssvg

SVG letters can not evenly spaced


I position each letter with 0, 12, 24, 36 etc... on x axis. I am expecting each letter will be spaced evenly, but they are not.

const websiteName = "websitename".split('');

<svg width="180" height="36" style={{display:"block"}}>
    {                  
       [...websiteName].map((letter, i) => (
           <text x={i*12} y="30" fontSize="22" key={i}>{letter}</text>
       ))
                    }
</svg>

Here is how it look like:

enter image description here

What is the cause and how to fix it?


Solution

  • Example 1: You may consider using a monospaced font, where each character has the same width. If you want to stick with a proportional font, you can calculate the width of each letter and adjust the x-coordinate accordingly. Here's an example of using a monospaced font:

    const websiteName = "websitename".split('');
    
    <svg width="180" height="36" style={{ display: "block" }}>
      {websiteName.map((letter, i) => (
        <text x={i * 12} y="30" fontSize="22" fontFamily="monospace" key={i}>
          {letter}
        </text>
      ))}
    </svg>
    

    Example 2: You can calculate the total width of all characters and then distribute the space evenly. Here's an updated version of your code to achieve this:

    const websiteName = "websitename".split('');
    
    const letterSpacing = 12;
    const totalWidth = websiteName.length * letterSpacing;
    
    <svg width={totalWidth} height="36" style={{ display: "block" }}>
      {websiteName.map((letter, i) => (
        <text x={i * letterSpacing} y="30" fontSize="22" key={i}>
          {letter}
        </text>
      ))}
    </svg>;