46

I'm using the <pre> tag to display preformatted text (including line breaks, spaces and tabs etc.) But large lines without line-breaks are shown in one line and a scroll bar is added.

I want to limit the width of the <pre> tag (such that large lines are broken up to come to new lines and no scroll is required. Is this possible or is there some other tag that I can use?

Code is something like:

$.post("contr.php", q1, function(data) {
    $("#el_text").html("< pre>"+data+"< /pre>");
});

3 Answers 3

92

An exhaustive way of supporting it in almost all browsers:

pre {
    white-space: -moz-pre-wrap; /* Mozilla, supported since 1999 */
    white-space: -pre-wrap; /* Opera */
    white-space: -o-pre-wrap; /* Opera */
    white-space: pre-wrap; /* CSS3 - Text module (Candidate Recommendation) http://www.w3.org/TR/css3-text/#white-space */
    word-wrap: break-word; /* IE 5.5+ */
}

I had the same problem not long ago and had found the solution here: http://codingforums.com/showthread.php?t=43293

1
  • From W3 Schools, white-space is CSS 1 while word-wrap is CSS 3. Sep 13, 2012 at 13:02
22
pre{
    white-space:pre-wrap;
}

..does what you want in Firefox and Chrome - wraps the lines but preserves whitespace. But unfortunately IE doesn't seem to support it (although I haven't looked in IE8 yet).

Edit: IE8 supports it.

0

If space is being allocated to the right of the block even after doing what Karim said Then maybe you have enclosed inside .

Table tag allocates space for the entire pre string even when the content may be word wrapped This leads to blank areas on right of pre block

In this case replace with some other tag, like div or paragraph

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.