• blog
  • portfolio
  • about
  • contact
 
Preserving line breaks in html
Refactoring the regex way of preserving line breaks into a pure CSS solution.

If you have ever created a web application where users have the ability to post html on your site, you are probably aware of some minor challenges with preserving your user's line breaks in thier content. This sort of requirement comes when you allow comments or any other sort of user entered information. There are many ways you can accomplish this. One of the more common ways I have seen is to use regex to parse out the returns and line feeds into actual html breaks. If you look around you might even see code that looks a lot like this:

link to actual jsfiddle

It works, sure, but did you know that you can accomplish this same trick to preserve line breaks in a much more elegant way using CSS? It's true, you can use the white-space property in CSS. Here is the same sample but this time using: white-space: pre-line; and no jQuery.

link to actual jsfiddle

There are even some property values of white-space in CSS that allow you to preserve the white space too. That use case is certainly less common though. Here is a list of the options available pulled from w3schools.com

  • normal - Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary. This is default.
  • nowrap - Sequences of whitespace will collapse into a single whitespace. Text will never wrap to the next line. The text continues on the same line until a br tag is encountered.
  • pre - Whitespace is preserved by the browser. Text will only wrap on line breaks Acts like the pre tag in HTML.
  • pre-line - Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary, and on line breaks.
  • pre-wrap - Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks.
  • inherit - Specifies that the value of the white-space property should be inherited from the parent element.
04/23/2012 04:19:32
Posted on 04/23/2012 04:19:32


blog comments powered by Disqus
steven hook
C#, ASP.NET MVC, JavaScript, Windows Store developer and speaker interested in learning more. Proud member of the Pittsburgh .NET user group.
extras