CSS: white-space

By Xah Lee. Date: . Last updated: .

White-space property

The white-space property controls line break at whitespace positions, and whether repeated whitespaces are collapsed into one single whitespace.

πŸ›‘ warning: this property is not just for text. It applies to any whitespace between inline elements.

white-space: normal
  • Newline character is changed to a space.
  • Repeated spaces shrink into a single one.
  • Long line is wrapped.

(Like in the HTML p tag.)

white-space: pre
  • Newline character force a wrap.
  • White space sequences are shown as they are.
  • No auto line wrap.

(Like in the HTML pre tag.)

This is very useful, when you have poem, song lyrics, or code, you want line wrap at newline positions, and no need to add br tag at the end of every line.

.x {
 white-space: pre;
}
white-space: pre-wrap
  • Newline character force a wrap.
  • Long line is automatically wrapped.
  • Repeated spaces are NOT shrinked into just one space.

This is very useful for computer code, even better than β€œpre” tag, because if you have a long line comment, it'll be wrapped in the display, but when user copies the code, there will not be extra newline.

// Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, β€œand what is the use of a book,” thought Alice β€œwithout pictures or conversation?”.
console.log( 3 )
white-space: pre-line

Like pre-wrap, but repeated spaces are shrinked into just one space.

white-space: break-spaces

Same as pre-wrap, except that:

  • Any sequence of preserved white space always takes up space, including at the end of the line.
  • A line breaking opportunity exists after every preserved white space character, including between white space characters.
  • Such preserved spaces take up space and do not hang, and thus affect the box's intrinsic sizes (min-content size and max-content size).
white-space: nowrap
  • Repeated spaces shrink into a single one.
  • Newline char is changed to space.
  • The element's width has no effect on line wrapping.

To force a wrap, use HTML β€œbr” tag.

Summary:

respect newline charpreserve spaces and tabswrap long lineEnd-of-line spaces
normalnonoβœ…Remove
preβœ…βœ…noPreserve
pre-wrapβœ…βœ…βœ…Hang
pre-lineβœ…noβœ…Remove
break-spacesβœ…βœ…βœ…Wrap
nowrapnononoRemove

Non-breaking whitespace

To prevent a line wrap at positions you do not want to happen, use the Unicode character named NO-BREAK SPACE. The HTML entity is  .