When displaying multi-line text (e.g. input from a TextArea) in a static element (e.g. DIV), extra white space and line breaks are ignored, resulting in one long line of text.
An older approach used to be to replace any line breaks with the <br />
tag, but there is a better approach that doesn't involve editing the content itself:
The CSS property white-space
values pre
, pre-wrap
, and pre-line
are three options to control how white space and line breaks are displayed. To preserve both extra white space and line breaks, the pre-wrap
value is the best choice. (pre
preserves white spaces and line breaks, but doesn't wrap. pre-line
preserves line breaks, but strips extra white space.)
Input:
<div style="white-space: pre-wrap; max-width: 50%; border: 1px solid #ddd;">
Some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps.
Short entry with extra white space.
Two extra lines above
</div>
Output:
Some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps some long text that wraps.
Short entry with extra white space.
Short entry with extra white space.
Two extra lines above