getting linebreaks in <pre> tags

Html

Html Problem Overview


I'm creating comment fields which are based on user input into textarea. But when I use <pre> tags I can't tell it to wrap properly inside the comments view.

I'm not stuck on using <pre> tags if there is a better way of doing it. Only reason I chose to use it was to keep linebreaks and whitespaces added by user.

I noticed there is a property called "width" for <pre>, but W3 notes it as deprecated, and it only breaks after so and so many characters, which isn't ideal either. (It also doesn't work with IE at all.)

Any suggestions?

Html Solutions


Solution 1 - Html

The usual approach is to convert single newlines in the input to “<br />”. (Double-newlines would normally introduce a new “<p>” element.) This doesn't cover multiple-whitespace-runs though; if you need to preserve those, you could replace each two-space sequence with a space and a non-breaking space ('  ', ' \xA0', or ' &#160;' as a character reference).

There is a CSS way you can retain literal newlines and whitespaces but still wrap when the line length is too short:

white-space: pre-wrap;

However this CSS 2.1 and CSS 3 property value is not supported cross-browser under its original name. Webkit (Safari, Chrome) picks it up; to get it to work under the other popular browsers, you have to add:

white-space: -moz-pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;

The ‘word-wrap’ is for IE, which as always has its own way of doing things.

Solution 2 - Html

The BEST Cross Browser Way (chrome, internet explorer, Firefox). It worked for me to get line breaks and shows exact text:

CSS:

xmp{ white-space:pre-wrap; word-wrap:break-word; }

HTML:

<xmp> your text or code </xmp>

Solution 3 - Html

You could display the pre elements with overflow:auto like here on SO:

<pre style="overflow:auto">Loremipsumdolorsitamet,consecteturadipisicingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.Excepteursintoccaecatcupidatatnonproident,suntinculpaquiofficiadeseruntmollitanimidestlaborum.</pre>

But the pre element is just intended for preformatted text like source code or plain text documents. Thus you should better add HTML line breaks (br element) or even paragraphs (p element).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpeirixView Question on Stackoverflow
Solution 1 - HtmlbobinceView Answer on Stackoverflow
Solution 2 - HtmlfeaccoView Answer on Stackoverflow
Solution 3 - HtmlGumboView Answer on Stackoverflow