search

Home  >  Q&A  >  body text

Line breaks in HTML are '\n'

<p>Is there a way to get HTML to correctly handle <code>n</code> newlines? Or do I have to replace them with <code><br /></code>? </p> <p><br /></p> <pre class="brush:html;toolbar:false;"><div class="text"> abc def ghi </div></pre> <p><br /></p>
P粉470645222P粉470645222501 days ago568

reply all(2)I'll reply

  • P粉345302753

    P粉3453027532023-08-28 10:18:32

    You can use the CSS white-space property to represent \n. You can also keep tabs as shown in \t.

    For newlines\n:

    white-space: pre-line;

    For newlines \n and tabs \t:

    white-space: pre-wrap;

    document.getElementById('just-line-break').innerHTML = 'Testing 1\nTesting 2\n\tNo tab';
    
    document.getElementById('line-break-and-tab').innerHTML = 'Testing 1\nTesting 2\n\tWith 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>

    reply
    0
  • P粉144705065

    P粉1447050652023-08-28 09:00:04

    This is to display line breaks and carriage returns in HTML. Then you don't need to do this explicitly. You can do this in CSS by setting the whitespace property pre-line value.

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

    reply
    0
  • Cancelreply