vy32 vy32 - 19 days ago 5
CSS Question

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

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 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. 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?

Answer

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

Example

jsFiddle.

Further Reading.