Html – Render a string in HTML and preserve spaces and linebreaks

csshtmlline-breaksnewlinewhitespace

I have an MVC3 app that has a details page. As part of that I have a description (retrieved from a db) that has spaces and new lines. When it is rendered the new lines and spaces are ignored by the html. I would like to encode those spaces and new lines so that they aren't ignored.

How do you do that?

I tried HTML.Encode but it ended up displaying the encoding (and not even on the spaces and new lines but on some other special characters)

Best Answer

Just style the content with 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>