3 ways to show line breaks in HTML without ever using br

Of course <br/> is what we all grew up with from our HTML beginnings, but there’s more.

Like… CSS white-space: pre-wrap:

HTML
<div id="box"> Coding is cognitively demanding, mentally stimulating, emotionally rewarding, beauty, unity power </div>
CSS
#box { background-color: #e0e0e0; width: 250px; font-family: Arial; white-space: pre-wrap; }

Without pre-wrap:

pre-wrap preserves line breaks and sequences of whitespace in the element’s text.

So the 4 spaces between the words in the first line are shown in the output along with the line break.

Even the space used for text indentation is also shown in the output, adding extra left padding to the container.

JS too

pre-wrap also acknowledges the \n character when set from JavaScript; with innerText or innerHTML:

JavaScript
const box = document.getElementById('box'); box.innerText = 'Coding is \n logic, art, growth, \n creation';

Without pre-wrap:

pre

pre works a lot like pre-wrap but no more auto wrapping:

For example:

HTML
<div id="box"> JavaScript at Coding Beauty HTML at Coding Beauty CSS at Coding Beauty </div>
CSS
#box { white-space: pre; background-color: #e0e0e0; width: 250px; font-family: Arial; }

If pre was pre-wrap in this example:

The behavior with pre is the same when you set the innerHTML or innerText property of the element to a string using JavaScript.

Newlines only

white-space:pre-line: Ignore extra spaces but show line breaks:

HTML
<div id="box"> Coding is growth unity power beauty </div>
CSS
#box { background-color: #e0e0e0; width: 250px; font-family: Arial; white-space: pre-line }

pre-line -> pre-wrap:

Like the previous two possible white-space values, pre-line works in the same way when you set the innerHTML or innerText property of the element to a string using JavaScript.



Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.


Leave a Comment

Your email address will not be published. Required fields are marked *