HTML Line Breaks With CSS

If you have text on the server that may have line breaks, you may have gone through a series of steps to get it to display properly.

First, if you weren't really thinking about it, you just dump the output to the screen. ASP.NET and others HTML encode it, so you generally don't have to worry about any kind of script injection. But the line breaks aren't handled properly.

<div id=output>@message</div> *@

Next thing to try, replacing line breaks with a BR tag. Of course, since it's encoded, the HTML shows up as text, and that's no good.

<div id=output>@(
    message.Replace("\r\n", "<br>").Replace("\n", "<br>").Replace("\r", "<br>")
)</div>

Ok, now you need to use Html.Raw, but you can't do it on the whole string because that will put the dangerous raw text into the page. So you have to encode the message, after replacing the line breaks, then get the raw HTML. That gets you the result you want, but it's really ugly.

<div id=output>@Html.Raw(
    HttpUtility.HtmlEncode(message)
     .Replace("\r\n", "<br>").Replace("\n", "<br>").Replace("\r", "<br>")
)</div>

Thankfully there's a CSS property for this - white-space pre-line will show line breaks properly with no extra work.

<div id=output style=white-space:pre-line;>@message</div>

View code on GitHub

Comments

Popular posts from this blog

C# Record Serialization

Add timestamp to photo using ImageMagick

Read/write large blob to SQL Server from C#