html - 在 HTML 中呈现字符串并保留空格和换行符

我有一个包含详细信息页面的 MVC3 应用程序。作为其中的一部分,我有一个包含空格和换行符的描述(从数据库中检索)。渲染时,新行和空格会被 html 忽略。我想对这些空格和新行进行编码,以便它们不会被忽略。

你是怎么做到的?

我尝试了 HTML.Encode,但它最终显示了编码(甚至不在空格和换行符上,而是在一些其他特殊字符上)

最佳答案

只需使用 white-space: pre-wrap; 设置内容样式即可.

div {
    white-space: pre-wrap;
}
<div>
This is some text   with some extra spacing    and a
few newlines along with some trailing spaces        
     and five leading spaces thrown in
for                                              good
measure                                              
</div>

https://stackoverflow.com/questions/9492249/

相关文章:

css - 即使没有内容,如何强制 DIV block 扩展到页面底部?

jquery - 在 jQuery 中查找所有未选中的复选框

html - 当鼠标移过表格中的一行时将光标更改为手形

html - 如何保存 Chrome 开发者工具样式面板的 CSS 更改?

html - 使用 :before and :after CSS selector to inser

html - 设置表格列宽

javascript - 使用 ng-include 时失去作用域

html - 在 Notepad++ 中格式化代码

html - 如何在 HTML 页面上显示原始 HTML 代码

email - 使电子邮件地址免受网页上的机器人攻击?