通过CSS将元素显示为预格式化文本

Dag*_*bit 100 html css whitespace pre

有没有办法pre通过CSS 模拟元素的显示?

例如,我可以使用CSS规则在此div中保持空格完整吗?

<div class="preformatted">

  Please procure the following items:

    - Soup
    - Jam
    - Hyphens 
    - Cantaloupe
</div>
Run Code Online (Sandbox Code Playgroud)

Bol*_*ock 163

使用white-space: pre保留空白预格式化作为pre元素.为了更进一步,还要添加font-family: monospace,因为pre默认情况下元素通常设置为等宽字体(例如,用于代码块).

.preformatted {
    font-family: monospace;
    white-space: pre;
}
Run Code Online (Sandbox Code Playgroud)
<div class="preformatted">

  Please procure the following items:

    - Soup
    - Jam
    - Hyphens 
    - Cantaloupe
</div>
Run Code Online (Sandbox Code Playgroud)

  • 在我等着接受这个答案时,你能解释一下`pre`和`pre-wrap`之间的区别吗?我假设`pre-wrap` ...换行? (4认同)
  • @GGG:没错。请参阅[比较](http://jsfiddle.net/BoltClock/2TA8g/1)。 (2认同)

小智 40

.preformatted {
   white-space: pre-wrap;
}
Run Code Online (Sandbox Code Playgroud)

我认为"预包装"更好.它可以帮助长线.


Dav*_*mas 10

是:

div.preformatted {
    white-space: pre;
    }
Run Code Online (Sandbox Code Playgroud)

参考: