htmlcsstags

<pre> tag in HTML with fixed width


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>");
});

Solution

  • An exhaustive way of supporting it in almost all browsers, copied verbatim from Willy Duitt's 2004 post on CodingForums.com:

    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+ */
    }