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

Last updated on February 12, 2024
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:

<div id="box">
  Coding   is cognitively  demanding,
   mentally    stimulating,
  emotionally  rewarding,
         beauty, unity

         power
</div>
#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:

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:

<div id="box">
  JavaScript     at     Coding Beauty
  HTML at Coding Beauty
  CSS   at   Coding Beauty
</div>
#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:

<div id="box">
  Coding   is    growth   unity
  power       beauty
</div>
#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.

See also