Desmoline Awa
Desmoline Awa

Reputation: 533

Is there a way to make the height of new line characters (\n) be less than the line-height of the text?

I'm building a reader to display text and the text comes with \n\n characters within it, and when rendered in HTML, it makes the empty lines' heights bigger than I want. Is there a way to control the height of the empty line produced in Html, without replacing them with Html tags?

See an example here. I want to reduce the height of that space, which is introduced by the \n\n characters in the text

Thanks in advance.

Upvotes: 0

Views: 506

Answers (1)

vanowm
vanowm

Reputation: 10221

You can do it by replacing empty lines with an empty HTML element:

const text = `this is an example
of multiline text.
spacing between these lines
is consistent, but line below will be different

even multiple empty lines:







will have the same height`;

const div = document.getElementById("main");
div.textContent = text;
div.innerHTML = div.innerHTML.replace(/([\n]{2,})/g, "<p>$1</p>");

console.log("original text length: ", text.length);
console.log("text from html length: ", div.textContent.length);
console.log("are both texts equal? ", div.textContent === text);
div
{
  white-space: pre;
  line-height: 2em;
}

p
{
  height: 2em;
  margin: 0;
  padding: 0;
  border: none;
  line-height: 0;
  visibility: hidden;
  white-space: none;
}
<div id="main"></div>

Upvotes: 1

Related Questions