【问题标题】:CSS to force XML display to maintain newlines but force word-wrapCSS 强制 XML 显示保持换行但强制自动换行
【发布时间】:2011-04-22 03:38:20
【问题描述】:

我有一个 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;
}

我得到了我的包装,但丢失了我的空白行。

有什么办法可以两者兼得?

【问题讨论】:

    标签: css xml newline word-wrap


    【解决方案1】:

    alex 给出的答案是正确的,但我仍然想详细说明他的答案。

    使用white-space: pre-wrap; 与使用&lt;pre&gt; 完全相同,只是它会根据其父级的边界自然换行。据我所知,使用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+ */
        }
    

    【讨论】:

    • 多么好的跨浏览器解决方案啊。谢谢!
    【解决方案2】:

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

    您可以使用white-space: pre-line 来获得您想要的。请记住,它在 Source.

    示例

    jsFiddle.

    Further Reading.

    【讨论】:

    • 哇!这就像一个魅力。我不知道该选项可用。我想这就是我通过谷歌搜索而不是查看文档所得到的。
    【解决方案3】:

    这个怎么样:

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

    【讨论】:

      【解决方案4】:

      这是我的 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 */
      }
      

      尊重休息。

      【讨论】:

      • 谢谢,但我更喜欢基于标准的解决方案。如果没有单元格,不确定您的系统会做什么?
      猜你喜欢
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 2023-02-25
      • 2017-06-28
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      相关资源
      最近更新 更多