How to set the space between characters in a text with JavaScript?

To set the space between characters in text, use the JavaScript letterSpacing property. This property controls the horizontal spacing between individual characters in a text element.

Syntax

element.style.letterSpacing = "value";

The value can be specified in pixels (px), em units, or other CSS length units. Negative values decrease spacing, while positive values increase it.

Example: Setting Letter Spacing

Here's a complete example that demonstrates how to set character spacing with JavaScript:

<!DOCTYPE html>
<html>
   <body>
      <h1>Letter Spacing Example</h1>
      <p id="myText">This is demo text with adjustable spacing.</p>
      <button onclick="increaseSpacing()">Increase Spacing</button>
      <button onclick="decreaseSpacing()">Decrease Spacing</button>
      <button onclick="resetSpacing()">Reset</button>
      
      <script>
         function increaseSpacing() {
            document.getElementById("myText").style.letterSpacing = "5px";
         }
         
         function decreaseSpacing() {
            document.getElementById("myText").style.letterSpacing = "-1px";
         }
         
         function resetSpacing() {
            document.getElementById("myText").style.letterSpacing = "normal";
         }
      </script>
   </body>
</html>

Different Letter Spacing Values

You can use various units and values for letter spacing:

<!DOCTYPE html>
<html>
   <body>
      <p id="text1">Normal spacing</p>
      <p id="text2">Tight spacing</p>
      <p id="text3">Wide spacing</p>
      <p id="text4">Em unit spacing</p>
      
      <script>
         // Different letter spacing values
         document.getElementById("text1").style.letterSpacing = "normal";
         document.getElementById("text2").style.letterSpacing = "-0.5px";
         document.getElementById("text3").style.letterSpacing = "8px";
         document.getElementById("text4").style.letterSpacing = "0.2em";
      </script>
   </body>
</html>

Common Values

Value Effect Use Case
normal Default spacing Reset to normal
2px Slight increase Improved readability
5px Wide spacing Headlines, emphasis
-1px Tighter spacing Condensed text

Conclusion

The letterSpacing property in JavaScript provides easy control over character spacing in text elements. Use positive values to increase spacing and negative values to decrease it for various typographic effects.

Updated on: 2026-03-15T23:18:59+05:30

504 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements