6
votes

Among <xmp>, <pre> or <code>, <xmp> have been recommended[1] to display HTML code.

Given html such as:

<xmp>
<div data-role="page" data-theme="b">
    <header></header>
    <div data-role="content">
            <ul data-role="listview" data-filter="true">
                <li><a href="index.html">Some</a></li>
                <li><a href="index.html">random</a></li>
                <li><a href="index.html">content</a></li>
                <li><a href="index.html">With a very long annoying line which naturally goes roge by going outside the main windows and requesting scrolling. So childish !</a></li>
            </ul>
    </div>
    <footer></footer>
</div><!-- page end-->
<script>      
someJS(parameter) { 
  $('header').append('hello!');
}
</script>
</xmp>

See working fiddle

One of my lines is very long and so, requires a lot of horizontal scrolling. How to word-break (force line jump) on <xmp> ?

I wish to display code (html, JS) without parsing nor scrolling.


[1]: Related : Is there a HTML/CSS way to display HTML tags without parsing? (suggest xmp without solution for line break)


Edit: Solution http://jsfiddle.net/hucY9/5/

xmp { white-space: pre-wrap }
2
Huh? You have to HTML-entity-encode your code so that it isn't interpreted as HTML and will actually display the < and >s and such. Then you probably want to use <pre> or <code> instead of <xmp> (which appears to be deprecated); you can use white-space: pre I think it is to keep the line breaks.mpen
Well, I wrote more to explain !Hugolpz

2 Answers

10
votes

Just as for pre, you can style xmp so that it is not really preformatted but lines wrap at spaces or other permitted line break points as needed, by setting

xmp {white-space: pre-wrap }

However, this makes a line break so that the second part starts at the very left, not with the same (or larger) indentation as the first part. This makes the code look messy.

Also note that line wrapping as implemented in browsers may turn the text invalid as HTML markup. For example, many browsers feel free to break after a hyphen, but e.g. an HTML attribute like data-filter must not be broken. Of course it would be just a matter of markup that the user sees, but still.

To create intelligent wrapping (as in many text editors and programming environments), you would need JavaScript or a more complicated setup where each line is an element of its own, indented using left margin in CSS, not with spaces.

6
votes

The BEST Cross Browser Way worked for me (chrome, internet explorer, Firefox).

It worked for me to get line breaks and shows exact code/text:

CSS:

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

HTML:

<xmp> your text or code </xmp>