CSS强制XML显示以维护换行但强制自动换行

时间:2011-04-22 03:38:20

标签: css xml newline word-wrap

我有一个XML文件,我试图仅通过添加CSS来显示。

XML有许多看起来像这样的元素:

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

我希望CSS保留换行符,但要自动换行文本。

如果我的CSS看起来像这样:

text {
    white-space: pre;
}

我得到了空白行,但文字偏离右边缘。

如果我的CSS看起来像这样:

text {
    width: 500px;
}

我得到了我的包装但却失去了空白。

有没有办法同时获得两者?

4 个答案:

答案 0 :(得分:2)

亚历克斯给出的答案是正确的,但我仍然想详细说明他的回答。

使用white-space: pre-wrap;与使用<pre>完全相同,只是它会根据其父级的边界自然地换行。据我所知,使用white-space: pre;不会尊重您的界限。当然,您需要跨浏览器兼容性。

我相信这就是你想要的:

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

答案 1 :(得分:1)

如果您有white-space: pre,则文本将保留原样,并保留所有格式(多个空格不会截断为一个),这就是为什么您的长文本行不会中断的原因。

您可以使用white-space: pre-line来获得所需内容。请记住,它不适用于&lt; IE8和IE9中的错误。 Source

实施例

Example

jsFiddle

Further Reading

答案 2 :(得分:0)

这个怎么样:

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

答案 3 :(得分:0)

这是我的hacky CSS解决方法 - 如果有空格,动态文本换行。如果没有空格,则包含元素将展开以适合内容:

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

休息受到尊重。

相关问题