Preserve line breaks in textarea

The line breaks the user entered are preserved, neither html nor php simply drops or alters anything. However html markup, when rendered for visualization uses a different way to code line breaks. There are very good reasons for that. So what you have to do is "translate" the existing line breaks into html style line breaks.

How to do that depends on the environment you are working under. In general you have to translate line break codes like \n to <br> tags. The php scripting language offers a function for this for example: nl2br()

However take care: this only applies when rendering the text as html markup. This does not apply, when you output the text into a textarea inside a form again to allow changing it for example. In that case you have to preserve the original line breaks just as received.

So what you typically do is: you save the unaltered text input as received. When outputting that text again to a client, say after reading it from a database where you have saved it before, then you know the situation, how the text will be presented. That is when you either translate or leave the existing line breaks as they are.

You could also encode unaltered text containing line breaks by <pre>...</pre> tags, so mark them as to be rendered as preformatted. THis is for example done when displaying source code in html pages.


Generally you just need to add

  • white-space: pre-line; whitespace trimmed to single whitespace or

  • white-space: pre-wrap; all whitespace preserved

to the element's style (CSS), where you want your text rendered with line-breaks.