Is there a way to make HTML properly treat n line breaks? Or I have to replace them with <br/>?

<div class="text">
  abc
  def
  ghi
</div>

0

This is to show new line and return carriage in HTML, then you don’t need to do it explicitly. You can do it in CSS by setting the white-space attribute pre-line value.

<span style="white-space: pre-line">@Model.CommentText</span>

1

You can use CSS white-space property for n. You can also preserve the tabs as in t.

For line break n:

white-space: pre-line;

For line break n and tabs t:

white-space: pre-wrap;
document.getElementById('just-line-break').innerHTML = 'Testing 1nTesting 2ntNo tab';

document.getElementById('line-break-and-tab').innerHTML = 'Testing 1nTesting 2ntWith tab';
#just-line-break {
  white-space: pre-line;
}

#line-break-and-tab {
  white-space: pre-wrap;
}
<div id="just-line-break"></div>

<br/>

<div id="line-break-and-tab"></div>

1

As per your question, it can be done by various ways.

For example if you want to insert a new line in a text area, you can use these:

&#10; line feed and &#13; carriage return, used like this:

<textarea>Hello &#10;&#13;Stackoverflow</textarea>

You can also use <pre>---</pre> preformatted text like this:

<pre>
  This is line 1
  This is line 2
  This is line 3
</pre>

Or you can use a <p>----</p> paragraph tag like this:

  
<p>This is line 1</p>
<p>This is line 2</p>
<p>This is line 3</p>

2

You could use the <pre> tag

<div class="text">
<pre>
  abc
  def
  ghi
</pre>
  abc
  def
  ghi
</div>

0

Using white-space: pre-line allows you to input the text directly in the HTML with line breaks without having to use n

If you use the innerText property of the element via JavaScript on a non-pre element eg a <div>the n values ​​will be replaced with <br> in the DOM by default

  • innerText: replace n with <br>
  • innerHTML, textContent: require the use of styling white-space

It depends on how your applying the text, but there are a number of options

const node = document.createElement('div');
node.innerText="n Test n One "

2

you can use <pre> tag :

<div class="text">
<pre>
abc
def
ghi
</pre>
</div>

0

Simple and linear:

 <p> my phrase is this..<br>
 the other line is this<br>
 the end is this other phrase..
 </p>

2

A simple and more natural solution that doesn’t involve CSS styles or numeric character references like &#13;&#10; would be to use the &NewLine; character entity reference:

The primary colors are:&NewLine;- Red&NewLine;- Green&NewLine;- Blue

Note: Since this is defined simply as the LF (line feed, or the U+000A Unicode code point) character, it can be debatable whether it suits scenarios where the entire CR + LF (carriage return + line feed) sequence is required. But then, it worked in my Chrome, Edge and WebView2 tests done in Windows 10, so it should be safe to use.

Not the answer you’re looking for? Browse other questions tagged html or ask your own question.