Last Updated: February 25, 2016
·
890
· tadas_t

Preserving line brakes in HTML

Often times one needs to display some multi-line text user input on a page, e.g. an address from a textarea field. Sometomes using a pre tag is an option, but the text can break out of the box and screw up the page layout.

I used to rely on Rails' simple_format helper for preserving line breaks. But I just learned you can do it purely with CSS

// HTML
<span class='with-linebreaks'>
  Some Lines
  here
</span>

// CSS
.with-linebreaks{ white-space: pre-wrap; }

pre-wrap behaves just like the pre tag, except that it adds extra line breaks to prevent the text breaking out of the element's box.

Eureka!

1 Response
Add your response

Here's a great run down on the various options for the CSS white-space property http://css-tricks.com/almanac/properties/w/whitespace/

over 1 year ago ·