How to set the distance between lines in a text with JavaScript?

To set the distance between lines in text, use the lineHeight CSS property via JavaScript. This property controls the vertical spacing between lines of text within an element.

Syntax

element.style.lineHeight = value;

The lineHeight value can be:

  • Number: Multiplier of font size (e.g., "2" = 2x font size)
  • Pixels: Fixed height (e.g., "30px")
  • Percentage: Relative to font size (e.g., "150%")

Example: Setting Line Height with Button Click

<!DOCTYPE html>
<html>
  <body>
    <h1>Line Height Demo</h1>
    <p id="myText">
      This is the first line of text.<br>
      This is the second line of text.<br>
      This is the third line of text.
    </p>
    
    <button onclick="setLineHeight()">Increase Line Height</button>
    <button onclick="resetLineHeight()">Reset Line Height</button>
    
    <script>
      function setLineHeight() {
        document.getElementById("myText").style.lineHeight = "2.5";
      }
      
      function resetLineHeight() {
        document.getElementById("myText").style.lineHeight = "normal";
      }
    </script>
  </body>
</html>

Example: Different Line Height Values

<!DOCTYPE html>
<html>
  <body>
    <div id="demo1">Normal line height (default)<br>Second line<br>Third line</div>
    <div id="demo2">Tight spacing<br>Second line<br>Third line</div>
    <div id="demo3">Loose spacing<br>Second line<br>Third line</div>
    
    <script>
      // Set different line heights
      document.getElementById("demo2").style.lineHeight = "1.2";
      document.getElementById("demo3").style.lineHeight = "3";
      
      // Using pixel values
      document.getElementById("demo1").style.lineHeight = "24px";
    </script>
  </body>
</html>

Common Line Height Values

Value Description Use Case
"normal" Browser default (usually 1.2) Reset to default
"1.5" 1.5x font size Good readability
"2" 2x font size Double spacing
"20px" Fixed 20 pixels Precise control

Conclusion

Use element.style.lineHeight to control line spacing in JavaScript. Number values (like "1.5") are most flexible as they scale with font size changes.

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

529 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements