开发者

CSS to force XML display to maintain newlines but force word-wrap

开发者 https://www.devze.com 2023-02-28 14:30 出处:网络
I have an XML file that I am attempting to display solely by adding a CSS. The XML has many elements that look like this:

I have an XML file that I am attempting to display solely by adding a CSS.

The XML has many elements that look like this:

<text>
this is some text.

Yeah, some text.
</text>

<text>
This is so开发者_JS百科me text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. 
</text>

I want the CSS to preserve line breaks but to automatically wrap the text.

If my CSS looks like this:

text {
    white-space: pre;
}

I get my blank lines, but the text goes off the right margin.

if my CSS looks like this:

text {
    width: 500px;
}

I get my wrapping but lose my blank lines.

Is there any way to get both?


The answer alex gave is correct, but I still want to ellaborate on his answer.

Using white-space: pre-wrap; is exactly the same as using <pre>, except that it will naturally wrap lines according to the boundaries of its parent. Using white-space: pre; will to my knowledge not respect your boundaries. And of course, you want cross-browser compatibility.

I believe this is what you want:

    #log {
        white-space: pre-wrap;       /* CSS3 */
        white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
        white-space: -pre-wrap;      /* Opera 4-6 */
        white-space: -o-pre-wrap;    /* Opera 7 */
        word-wrap: break-word;       /* Internet Explorer 5.5+ */
    }


If you have white-space: pre, the text is preserved as is with all formatting (multiple whitespace is not truncated to one) so that is why your long lines of text are not breaking.

You can use white-space: pre-line to get what you want. Keep in mind it doesn't work in < IE8 and is buggy in IE9. Source.

Example

CSS to force XML display to maintain newlines but force word-wrap

jsFiddle.

Further Reading.


How about this:

text {
    white-space: pre;
    width: 500px;
}


This is my hacky CSS workaround - dynamic text wraps if there is a space. If there is no space, the containing element expands to fit the content:

text {
  width: 120px; /* sets the width text will wrap into if there are spaces */
  display: table-cell; /* expands the element to fit text if it can't break */
}

Breaks are respected.

0

精彩评论

暂无评论...
验证码 换一张
取 消