How to Preserve Newlines, Line Breaks, and Whitespace in an HTML String

Sometimes you want to display the content in the same format as typed in a textarea. For example, a text from a textarea may contain line breaks or empty lines.

The white-space CSS property is helpful displaying the text in the same way it’s provided by the user. No extra effort for you to parse and format the string yourself!

Preserve Newlines, Line Breaks, and Whitespace in HTML

Use the white-space: pre; setting to display long-form content containing whitespace and line breaks the same way as provided by a user. The text will also stay inside the container boundaries and now overflow the parent:

<span style="white-space: pre;">  
  This is a long-form text.

  The content includes whitespace, line breaks with newlines. If the line becomes white long, it needs to wrap.

  This is a new paragraph.
</span>  

And here’s how a text looks like with CSS styling white-space: pre-wrap;:

Preserve Whitespace and Newlines in an HTML string and also wrap text with `white-space: pre-wrap`

If you want your text to overflow the parent’s boundaries, you should use pre as your CSS whitespace property. Using white-space: pre wraps still preserves newlines and spaces.

The difference to white-space: pre-wrap is that a long, single line of text may render outside of the parent container:

<span style="white-space: pre-wrap;">  
  This is a long-form text.

  The content includes whitespace, line breaks with newlines. If the line becomes white long, it needs to wrap.

  This is a new paragraph.
</span>  

And here’s how a text looks like with CSS styling white-space: pre;:

Preserve Whitespace and Newlines in an HTML string with `white-space: pre`

Enjoy!

Explore the Library

Find interesting tutorials and solutions for your problems.