CSS: white-space
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
ptag.) white-space: pre-
- Newline character force a wrap.
- White space sequences are shown as they are.
- No auto line wrap.
(Like in the HTML
pretag.)This is very useful, when you have poem, song lyrics, or code, you want line wrap at newline positions, and no need to add
brtag 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-contentsize andmax-contentsize).
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 char | preserve spaces and tabs | wrap long line | End-of-line spaces | |
|---|---|---|---|---|
normal | no | no | β | Remove |
pre | β | β | no | Preserve |
pre-wrap | β | β | β | Hang |
pre-line | β | no | β | Remove |
break-spaces | β | β | β | Wrap |
nowrap | no | no | no | Remove |
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 .